Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

array from a seperate class

Hi,

I want to know how to create an array in a seperate class and then print the contents of an array from an another class. When I try to do this I just get a garbage value when I print the contents of the array in the second class even though I assigned a value to the array. I really need your help!!

Thanks,
Sunny
[341 byte] By [sunnny] at [2007-11-11 6:54:24]
# 1 Re: array from a seperate class
Hi,

I want to know how to create an array in a seperate class and then print the contents of an array from an another class. When I try to do this I just get a garbage value when I print the contents of the array in the second class even though I assigned a value to the array. I really need your help!!

Thanks,
Sunny

Something like this?
public class PrintArray {
public static String printIntArray(int[] array) {
if(array == null || array.length == 0) return "[empty]";
StringBuffer strb = new StringBuffer("int array: ["+array[0]);
for(int i = 1; i < array.length; i++) {
strb.append(", "+array[i]);
}
strb.append("]");
return strb.toString();
}
}

And to test the class:
public class Test {
public static void main(String args[]) {
int[] array = {1,2,3,4,5};
System.out.println(PrintArray.printIntArray(array));
}
}

Good luck.
prometheuzz at 2007-11-11 22:39:58 >
# 2 Re: array from a seperate class
...the temptation to make this a bit more generic:

public class PrintArray {
StringBuffer sb = new StringBuffer();
public String printAnyArray(Object anArray) {

if (anArray==null) return "[null]";

sb.setLength(0);
sb.append("[");

if (anArray instanceof int[]) {
int [] ii=(int[])anArray;
if (ii.length==0) return "[empty]";
for (int i=0; i<ii.length; i++) sb.append(ii[i]+" ");
}
else if (anArray instanceof float[]) {
float [] ff=(float[])anArray;
if (ff.length==0) return "[empty]";
for (int i=0; i<ff.length; i++) sb.append(ff[i]+" ");
}
else if (anArray instanceof double[]) {
double [] dd=(double[])anArray;
if (dd.length==0) return "[empty]";
for (int i=0; i<dd.length; i++) sb.append(dd[i]+" ");
}
else if (anArray instanceof Object[]) {
Object [] oo=(Object[])anArray;
if (oo.length==0) return "[empty]";
for (int i=0; i<oo.length; i++) sb.append(oo[i]+" ");
}

sb.append("]");
return sb.toString();
}

public static void main(String args[]) {
PrintArray pA=new PrintArray();
int[] iArray = {
1, 2, 3, 4, 5};
double [] dArray = {
1.4,1.5,1.6
};
String [] strArray= {
"One","Two","Three"
};
CustClass [] ccArray= {
new CustClass(11),
new CustClass(22),
new CustClass(33)
};
System.out.println(pA.printAnyArray(iArray));
System.out.println(pA.printAnyArray(dArray));
System.out.println(pA.printAnyArray(strArray));
System.out.println(pA.printAnyArray(ccArray));
}
}
class CustClass {
int val=Integer.MIN_VALUE;
public CustClass(int val) {
this.val=val;
}
public String toString() {
return "*"+val+"*";
}
}
sjalle at 2007-11-11 22:41:03 >