Search code examples
javasymbolscannot-find-symbol

Why do I get a 'cannot find symbol' error in this program?


When I run the following program, I get a 'cannot find symbol' error. It is probably caused by a stupid mistake, but I have spent about an hour trying to fix it and I have no idea what the problem is. Here is the code:

import java.util.*;

public class Purse{

   private ArrayList<String> coins;

   public Purse(){
      coins = new ArrayList<String>();
   }

   public void addCoin(String coin){
      if(coin == "Quarter" || coin == "Dime" || coin == "Nickel")
         coins.add(coin);
   }

   public void removeCoin(String coin){
      coins.remove(coin);
   }

   public void transfer(Purse other){
      for(int i = 0; i < other.coins.size(); i++)
         coins.add(other.coins.get(i));
         other.remove(i);

   }

}

and here is the error it gives me:

Purse.java:23: error: cannot find symbol
         other.remove(i);
                      ^
  symbol:   variable i
  location: class Purse
1 error

the program is supposed to be 'moving' items from one ArrayList to another.


Solution

  • when you do this

      for(int i = 0; i < other.coins.size(); i++)
             coins.add(other.coins.get(i));
             other.remove(i);
    

    without { } then is only the followinhg line the one that is embedded in the for scope...

    so basically, for this statement:

    other.remove(i); 
    

    the variable i is not defined....

    on the other hand:

    this will never work for comparing strings

    coin == "Quarter"