0

I have been trying to make a simple program in eclipse indigo, but kept getting the same problem, so I made this test to see the code in the simplest way. It looks like this:

import java.util.Scanner;
public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

Scanner input = new Scanner(System.in);

System.out.println("Please enter a letter");

String answer = input.nextLine();

if(answer == "a"){

System.out.println("a equals 1");

}

else if(answer == "b"){

System.out.println("a equals 2");

}

else{

System.out.println("a is not 1 or 2");

}

input.close();
    }

}

My problem seems to be in the line

String answer = input.nextLine();

I found this small piece of information after a lot of testing. If I change the code so it will use integers it will work, but it seems to have some problems with the String. Does anyone know what's wrong?

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
H. R.
  • 1
  • 1
    Try to change == into .equals(). i.e (answer == "a") into answer.equals("a"). – BachT Aug 03 '15 at 03:35
  • Whenever you compare strings in Java YOU HAVE TO use equals or equalsIgnoreCase , so in this case you need to type: if(answer.equals("a")). Hope this helps! – HenryDev Aug 03 '15 at 05:56
  • Oh my goodness! I can't believe that I didn't think of that! Thank you so so much! – H. R. Aug 04 '15 at 20:22

0 Answers0