user1226589
user1226589

Reputation:

My program successfully compiled and run yet displays wrong output

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!");
    }
}
}

Upvotes: 0

Views: 271

Answers (2)

Shivasubramanian A
Shivasubramanian A

Reputation: 4456

You are doing string comparison in Java using ==, which is generally not recommended, since == does object comparison and not actual string comparison.

Try using the equals() method.

That is, change your code from

if(ans == "YES"){
    System.out.print("Correct!");
}

else if (ans == "NO"){
    System.out.println("Wrong!");
}

to

if(ans. equals("YES")){
    System.out.print("Correct!");
}

else if (ans.equals("NO")){
    System.out.println("Wrong!");
}

Upvotes: 1

amit
amit

Reputation: 178461

if(ans == "YES"){

You should use equals() to compare strings and not operator==

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]

Upvotes: 7

Related Questions