Search code examples
javafinalgridworld

How to make an array final?


I cannot seem to figure out this error that says "world must be declared final". Any advice? I am making a gridworld project (matching game). The segment

  temparray.add(world.getLocation().getColor() );

requires it to be final... But adding final world.get etc etc says illegal start of expression.

import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.*;
import info.gridworld.grid.*;
import info.gridworld.world.*;



import java.awt.Color;
import java.util.ArrayList;

public class cardGameDriver extends ActorWorld
   {
   public static void main( String[] args )
  {
  World world = new World();
  world.show();

  world.add( new card1());
  world.add( new card1()); 
  world.add( new card2()); 
  world.add( new card2());
  world.add( new card3());
  world.add( new card3());
  world.add( new card4());
  world.add( new card4());
  world.add( new card5());
  world.add( new card5());
  world.add( new card6());
  world.add( new card6());
  world.add( new card7());
  world.add( new card7());
  world.add( new card8());
  world.add( new card8());
  world.add( new card9());
  world.add( new card9());
  world.add( new card10());
  world.add( new card10());
  world.add( new card11());
  world.add( new card11());
  world.add( new card12());
  world.add( new card12());
  world.add( new card13());
  world.add( new card13());
  world.add( new card14());
  world.add( new card14());
  world.add( new card15());
  world.add( new card15());
  world.add( new card16());
  world.add( new card16());
  world.add( new card17());
  world.add( new card17());
  world.add( new card18());
  world.add( new card18());
  System.out.println( "Time yourself to see how fast you can make all 18 matches." );


  ArrayList<cards> temparray = new ArrayList<cards>();


  java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager() 
  .addKeyEventDispatcher(new java.awt.KeyEventDispatcher() 
  {
  public boolean dispatchKeyEvent(java.awt.event.KeyEvent event) 
     { 
     String key = javax.swing.KeyStroke.getKeyStrokeForEvent(event).toString(); 
     int x = 0;
     if (key.equals("pressed ENTER")) 
        {
        temparray.add(world.getLocation().getColor() );
        x++;
        if( x == 2 )
           {
           if( temparray.get(0) == temparray.get(1) )
              {
              System.out.println( "User has made a match!" );
              }
           else
              {
              System.out.println( "Try again!" );
              }
           x = 0;
           }
        }
     return true; 
       } 
  }); 

  }

}


Solution

  • Since you're trying to use a local variable inside a local class in a method, the variable must be declared final. So, just add the final modifier to the variable declaration:

    final World world = new World();
    

    Similar for other variables that are local to main method and not for the local class e.g. temparray.