0

I have a simple program run in the console which accepts inputs, creates objects based on these and saves those objects into a list. If however a "x" is entered, the function stops.

public static void input(List<Things> slist) {
    String strA = new java.util.Scanner(System.in).nextLine();
    if(!xcheck(strA) {return;}
    Things s = new Things(strA);
    slist.add(s);
}

public static boolean xcheck(String xStr){
if(xStr == "x"){
        return false;
    } else {
        return true;
    }
}

The problem is that the function xcheck never returns false. It does recognise that the input string contains "x" (xStr.contains("x")), but it doesn't seem to think that the input is only "x", even though when ouptutting the string into the console, it definately only outputs the "x" without anything else and the length of the String is 1.

Jason C
  • 38,729
  • 14
  • 126
  • 182

2 Answers2

2

Strings are comared with equals not ==.

Try:

public static boolean xcheck(String xStr){
if("x".equals(xStr)){
        return false;
    } else {
        return true;
    }
}
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • It may not even be worth the time to answer these; it's all explained pretty well in http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. – Jason C Mar 16 '14 at 17:44
2

Use xStr.equals("x") instead of xStr == "x".

Ebbe M. Pedersen
  • 7,250
  • 3
  • 27
  • 47