This question already has an answer here:
- How do I compare strings in Java? 23 answers
import java.util.Scanner;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// Attempt 1
String r = input.next();
if(r=="bu") {
System.out.println("- application terminated - ended by user");
System.exit(0);
}
// Attempt 2
String r = "bu";
if(r=="bu"){
System.out.println("- application terminated - ended by user");
System.exit(0);
}
}
Thats the stripped down code.
Attempt 1 didnt work, even tho the scanner did get the input "bu" from the console right (checked that by printing out r). Yet somehow the if-clause was not executed (The sysout wasnt even printed).
With Attempt 2 it worked perfectly, so something has to be wrong with the scanner or its detected value in Attempt 1, but I wasnt able to determine what.
Unfortunately the scanner is mandatory for the task, so how can I fix it? Please help!
Aucun commentaire:
Enregistrer un commentaire