2

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?

3
  • Does it say on what line it's expecting the .class? Commented Apr 9, 2014 at 17:31
  • provide us with diagnostics Commented Apr 9, 2014 at 17:32
  • I have upated the question @AntonH. Thanks Commented Apr 9, 2014 at 17:35

2 Answers 2

5

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];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Dude its first time I cam across this.
Why Declaration is not considered a statement?
As the body of an if or else, it's useless. It goes out of scope immediately.
1

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];

3 Comments

Nice way to do initialisation. Thanks
It does allow initialisation but the scoping rules of if statements override that. This all leads to better program stability.
So because a block specifies the scope in Java the buffer is going out of scope after the if block and is not available for the rest of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.