Let's say you have an integer array and a string array. You have to write a SINGLE method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.
You are given code in the editor. You have to complete it so that it prints the following lines:
1
2
3
Hello
World
You should not use method overloading (your answer will not get accepted).
Solution 1: For printArray method :
import java.io.IOException;
import java.lang.reflect.Method;
class Printe
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(int i=0;i<ar.length;i++){
System.out.println(ar[i].toString());
}
}
}
}
Solution 2 : For printArray Method :
import java.io.IOException;
import java.lang.reflect.Method;
class Printer
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(Object obj: ar){
if(obj instanceof String || obj instanceof Integer){
System.out.println(obj.toString());
}
}
}
}
}
import java.io.IOException;
import java.lang.reflect.Method;
class Printe
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(int i=0;i<ar.length;i++){
System.out.println(ar[i].toString());
}
}
}
}
Solution 2 : For printArray Method :
import java.io.IOException;
import java.lang.reflect.Method;
class Printer
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(Object obj: ar){
if(obj instanceof String || obj instanceof Integer){
System.out.println(obj.toString());
}
}
}
}
}
// Already Provided code by them for testing printArray Method.
public class Solution
{
public static void main( String args[] )
{
Printer myPrinter=new Printer();
Integer[] intArray = { 1, 2, 3 };
String[] stringArray = {"Hello","World"};
myPrinter.printArray( intArray );
myPrinter.printArray( stringArray );
int count=0;
for (Method method : Printer.class.getDeclaredMethods()) {
String name = method.getName();
if(name.equals("printArray"))
count++;
}
if(count>1)System.out.println("Method overloading is not allowed!");
assert count==1;
}
}
No comments:
Post a Comment