0

okay so I have this first class that breaks down a string, strips the spaces and everything, puts it into an Arraylist and feeds it to this parseRec class. For some reason when the first character is "+" it does not register for this first if statement. It surpasses it ang goes to the else statement which is supposed to only take integers. any ideas why?

public static Expression parseRec(ArrayList<String> list) {
    while (list.size() != 0) {
        if (list.get(i) == "+") {
            System.out.println("got this far");
                    .....................

        else {
            System.out.println(list.get(i));
            String intE = list.get(i);
            Expression intExp = new IntExpression(intE);
            list.remove(i);
            return intExp;
        }
    }

3 Answers3

1

Compare Strings with the equals() method:

if (list.get(i).equals("+")) {

instead of:

if (list.get(i) == "+") {

The == compares references and not the string contents. To compare two String objects' contents, never use ==.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1

Rewrite this portion

 if (list.get(i) == "+") {
        System.out.println("got this far");
                .....................

as

 if (list.get(i).equals("+")) {
        System.out.println("got this far");
                .....................

Comparison of String should be made by .equals() for exact comparison of value.

Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
  • I dont see i defined anywhere. It is likely that list.get(i) is undefined and therefore not == "+" then going to the else – clancer Feb 19 '14 at 00:22
  • The portion of code having the issue likely is this. @clancer Yes I do agree, i is not defined and it goes to the compilation issue if not defined. Its not about compilation issue. – Vinay Veluri Feb 19 '14 at 00:25
0

i would probably do

if ("+".equals(list.get(i))

to avoid NullPointerException in case list.get(i) is null

harshit
  • 7,925
  • 23
  • 70
  • 97