Reputation: 2924
Here in the following code I am trying to print the difference of two arrays but I am getting this class error: '.class' expected
Its coming on here
ArrayCopy9526.java:15: error: '.class' expected
int[] buffer = new int[array1];
And below is my full code.
public class ArrayCopy9526 {
public static void main(String[] args){
int[] sourceArr = {0,1,23,4,45,5,667,7,764,8,23};
int[] arrayAno = {2,3,34,45,456,56,13,123,8,23};
arrayDiff(sourceArr, arrayAno);
}
public static void arrayDiff(int[] arrayOne, int[] arrayTwo){
int array1 = arrayOne.length;
int array2 = arrayTwo.length;
if(array1 < array2)
int[] buffer = new int[array1];
else
int[] buffer = new int[array2];
for(int i = 0; i < array1; i++ ){
for(int j= 0; j < array2; j++) {
if(arrayOne[i] != arrayTwo[j]){
buffer[i] = arrayOne[i];
}
}
}
for(int i :buffer){
System.out.println(i);
}
}
}
What's wrong with this code?
Upvotes: 2
Views: 228
Reputation: 234865
buffer
goes out of scope at the end of the if
statement.
Declare buffer
before the if
or use a ternary operator:
int[] buffer = new int[array1 < array2 ? array1 : array2];
Upvotes: 1
Reputation: 178323
For the bodies of your if
and else
, you must have a statement or a block, not a declaration. The ".class expected" message is confusing, but it comes on the declaration. "Not a statement" might have been a clearer message.
Declare your buffer
before your if
and assign it in your if
and else
.
int[] buffer;
if(array1 < array2)
buffer = new int[array1];
else
buffer = new int[array2];
Upvotes: 5