-1

I've written a simple program to check if the input is the letter O or not. For some reason, even when I type the letter O, the program outputs that the input is not the letter O. I have used the Eclipse debugger to ensure that the input variable actually equals "O".

import java.util.Scanner;

public class scannerTest {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Give your input. I will tell you if your input is 'O' or not");
    String input = scan.next();
    if (input == "O"){
        System.out.println("Your input was 'O'");
        }
    else {
        System.out.println("Your input was not 'O'");
    }
}

}
Adrian Heine
  • 4,051
  • 2
  • 30
  • 43

2 Answers2

3

You need to use the equals method instead of the == operator, like this:

if(input.equals("O"))

Using == compares the memory address of the string objects instead of their values so in order for == to return true you would have to be comparing the same String object.

clav
  • 4,221
  • 30
  • 43
  • Ah, I knew it was something trivial. Hopefully such questions are tolerated on StackOverflow. I'll accept your answer in 15 minutes, when I can. Thanks! – WeierstrassSauce May 21 '13 at 02:02
  • 2
    @WeierstrassSauce sorry to say but no, this is a duplicate question. Duplicated questions are not welcomed on SO. – Luiggi Mendoza May 21 '13 at 02:05
  • Ah, I didn't realize the problem was the comparing of the strings. I would've searched for that if that was the case. – WeierstrassSauce May 21 '13 at 02:11
  • @WeierstrassSauce if you debugged the program you would have noticed that the problem was in the string comparison to begin with. – Luiggi Mendoza May 21 '13 at 02:16
1

== operator checks for the equality of Objects rather than the value of the String.

Instead of that, use:

if(input.equals("O")){
   //Code here
}
totymedli
  • 29,531
  • 22
  • 131
  • 165
Yash Sharma
  • 1,674
  • 2
  • 16
  • 23