-3

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.

wes1099
  • 98
  • 1
  • 7
  • also see [how do i compare Strings in java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – SomeJavaGuy Jan 31 '17 at 13:30
  • 4
    You need braces with your `for` loop. – Kevin Jan 31 '17 at 13:30
  • 2
    You need to use brackets to surround the code which you intend to be executed by the `for` loop. But besides that, you should not be comparing strings using `==`. – Tim Biegeleisen Jan 31 '17 at 13:30
  • This is why you should **always** use braces for any block statements, even if they only contain one statement. – JonK Jan 31 '17 at 13:34

1 Answers1

2

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" 
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97