0

I'm trying to build a program which reads a certain String after using the Split function

import java.util.Scanner;

   public class Lexa2 {

public void doit() {
    String str = "( 5 + 4 ) * 2";
    String [] temp = null;
    temp = str.split(" "); 
    dump(temp);
}
public void dump(String []s) {
    for (int i = 0 ; i < s.length ; i++) {           
        if (s[i] == "(") {              
            System.out.println("This is the left paren");
        } else if (s[i] == ")"){                
            System.out.println("This is the right paren");          
        }else  if (s[i] == "+"){                
            System.out.println("This is the add");          
        }else  if (s[i] == "-"){                
            System.out.println("This is the sub");          
        }else  if (s[i] == "*"){                
            System.out.println("This is the mult");         
        }else  if (s[i] == "/"){                
            System.out.println("This is the div");          
        }else               
            System.out.println("This is a number");
    }
}   

     public static void main(String args[]) throws Exception{
       Lexa2 ss = new Lexa2();
         ss.doit();
 }
    }

The output should be something like this:

This is the left paren
this is a number
this is the add
this is the right paren
this is a number
user unknown
  • 35,537
  • 11
  • 75
  • 121
Lu Yas
  • 137
  • 2
  • 5
  • 16

2 Answers2

4

you're pretty close, just replace (s[i] == "?") with (s[i].equals("?"))

pstanton
  • 35,033
  • 24
  • 126
  • 168
1

Don't use s[i] == ")" to compare strings. In this way, you're not checking if the string in s[i] is equal to ).

Use the equals method. Then you can compare the strings using:

if (s[i].equals("("))

Replace equals in the other if statements.

UPDATE

P.S. I think the best way to compare strings, looking to your code, is to use the switch/case statements. But, this feature is only available in Java 7. I think this will avoid the continuous checking with if statements, and the code will be more readable. If you have Java 7, use this feature, otherwise, in case of Java 6 or lower, follow @pstanton suggestion. ;-)

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
  • 1
    switches don't work with strings, so he/she would need to use char – pstanton May 12 '12 at 01:50
  • @pstanton You're right, indeed this feature is available only in Java 7. Thank you :-) Answer updated! For further info, take a look to: http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java – Alberto Solano May 12 '12 at 09:43