0

When I debug this code I noticed that the If statement does not ever switch the boolean type sales variable to true... This is bugging me because I know that answer = "y" when it gets to the If statement. Help please! and yes I did import java.util.Scanner

Scanner input = new Scanner(System.in);
boolean sales = false;
String answer;

System.out.print("Will you be calculating the Sales department pay aswell? (y or n):");
answer = input.nextLine().trim();

if (answer == "y")
{
    sales = true;
}

i have

Zong
  • 5,920
  • 5
  • 28
  • 46

2 Answers2

1

The correct way to compare strings is:

if (answer.equals("y"))

Notice that in Java equals() is used for testing equality between objects, whereas the == operator is used for testing identity. They're two different concepts, and most of the time you're interested in equality.

As the @MadProgrammer suggests, inverting the comparison order is a good idea - it'll be safer in case answer is null:

if ("y".equals(answer))
Óscar López
  • 225,348
  • 35
  • 301
  • 374
0

You should use equals() to compare strings:

if (answer.equals("y")) {
NPE
  • 464,258
  • 100
  • 912
  • 987