My program must display whether the answer to the question “Is 10>2” is correct, wrong or the user must have had wrong input. Even if I type “YES” or “NO”, it will still display WRONG INPUT. It is a very, very simple program. However, I’m a newbie. Any help will be appreciated.
import java.util.Scanner;
public class yesorno{
public static void main (String args[]){
Scanner answer = new Scanner(System.in);
String ans;
System.out.println("Answer with a YES or NO");
System.out.println("Is 10>2?");
System.out.print("Answer:");
ans = answer.next();
if(ans == "YES"){
System.out.print("Correct!");
}
else if (ans == "NO"){
System.out.println("Wrong!");
}
else{
System.out.println("Wrong input!");
}
}
}
You should use
equals()to compare strings and notoperator==Note that
operator==will yield true only if the two objects are actually the same object, and it is not the case.You should replace it to
if(ans.equals("YES")) {[and do the same for all other conditions in your program]