0

I am trying to implement the System.exit(0); in java to terminate my program when the word "exit" is typed into the console. I wrote the following method:

    public static void exit(){

    Scanner input = new Scanner(System.in);
    Str1 = input.next(String);

    if (str1 = "exit"){

        System.exit(0);
    }

    else if (str1 = "clear"){

        System.out.println("0.0");
    }       
}

and it doesn't seem to be working. Does anyone have any suggestions?

Thanks P.S the "clear" is just supposed to return 0.0 when "clear" is entered into the console, if you could not already tell.

braX
  • 11,506
  • 5
  • 20
  • 33
Charlie Tidmarsh
  • 37
  • 1
  • 1
  • 2

5 Answers5

4

Compare strings with equals() not with ==.

The reason is that == just compares object references/primitives,where as String's .equals() method checks equality.

if (str1.equals("exit")){

}

and also

else if (str1.equals("clear")){

}

Might useful :What are the benefits of "String".equals(otherString)

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1
if(str.equals("exit")) 

or

if(str.equalsIgnoreCase("exit")) 

or

if(str == "exit") 

instead of

if (str1 = "exit"){
newuser
  • 8,338
  • 2
  • 25
  • 33
1

With if (str1 = "exit") you use an allocation instead of a compare. You can compare with the equals() method.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
JulianG
  • 1,551
  • 1
  • 19
  • 29
0

Use the String.equals(String other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

So use:

if ("exit".equals(str1)){

}
code_fish
  • 3,381
  • 5
  • 47
  • 90
0

Besides equals(), the input.next(String pattern); require pattern not String data type

Change your code to:

public static void exit(){   

Scanner input = new Scanner(System.in);
str1 = input.next(); //assumed str1 is global variable

if (str1.equals("exit")){

    System.exit(0);
}

else if (str1.equals("clear")){

    System.out.println("0.0");
}

}

Notes : http://www.tutorialspoint.com/java/util/scanner_next_string.htm

gjman2
  • 912
  • 17
  • 28
  • 2
    Change `str1 = input.next();` to `String str1 = input.next();`, except if `str1` is a global variable – JulianG Oct 11 '13 at 07:51