Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and checking strings from user input

I have this code:

import java.util.Scanner;

public class Example {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    String answer = input.nextLine();

    if(answer == "yes"){
        System.out.println("Yea I programmed this right!");
    }else{
        System.out.println("Awww :(");
    }
  }
}

But when I run it and type yes, it should be saying

"Yea I programmed this right!"

but it says

"Awww :("

like image 284
Cole Avatar asked Dec 28 '11 21:12

Cole


2 Answers

You're comparing strings incorrectly. You must use the equals() method, like this:

if (answer.equals("yes"))

When you're programming in Java, the operator == is generally used for comparing primitive data types (int, double, etc.). If you use == for comparing two object types (like strings), you're comparing them for identity, that is, checking if they reference the same object in memory. In your case, what you need is to compare if they're equal: if they have the exact same value (a string of characters in this case) even if they're two different objects - and for that you must use the equals() method.

EDIT :

Even better, for preventing a NullPointerException, it's considered a good practice flipping the order of the comparison and writing first the string you're comparing with, like this:

if ("yes".equals(answer))

The explanation is simple: if for some reason answer is null, the above comparison will evaluate to false (meaning: answer is not "yes"), whereas the first version of the code would cause a NullPointerException when trying to call the equals() method on a null value.

like image 102
Óscar López Avatar answered Sep 23 '22 15:09

Óscar López


if(answer == "yes"){

should be

if("yes".equals(answer)){

(== is not correct for String equality, and we handle the case where answer is null)

like image 28
Matthew Gilliard Avatar answered Sep 23 '22 15:09

Matthew Gilliard