2

I have this code:

Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
String l =reader.next();
String[] a = new String[2];

a[0] = l ;
a[1] = "5";

if((String) a[0] == "5" )
{
    System.out.println("hey");
}

however if I enter "5" as my input, "hey" is not printed how do I get it so that I can use an if statment to see if what is entered is a certain character or word

3 Answers3

1

Use a[0].equals("5"), == is just checking if they're the same object rather than string content.

splrs
  • 2,424
  • 2
  • 19
  • 29
0

You should to compare array member with equals method, regarding to that is the String.

You should to use this:

if(a[0].equals("5") )
{
    System.out.println("hey");
}

instead of

if((String) a[0] == "5" )
{
    System.out.println("hey");
}

In that case you will check content, not the reference.

Bosko Mijin
  • 3,287
  • 3
  • 32
  • 45
0

Use nextInt() to get integer

Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
int l =reader.nextInt();
if(l == 5 )
{
   System.out.println("hey");
}
Hammad
  • 101
  • 1
  • 10