0

I'm trying to have user input where user types a letter and then depends on letter 'IF' statement chooses which fields to display.

What I have now if I type 'p' and 'P' or 'F' or 'f' my 'for' statement still don't understand my input and throws me to 'else' statement.

But why not?

        Scanner scanner = new Scanner(System.in);

        System.out.print("Employee's Last Name: ");
        inputName = scanner.next();
        System.out.print("Employment Status (F or P): ");
        inputStatus = scanner.next();

        if (inputStatus == "F" || inputStatus == "f")
        {
            // some code
        }
        else if(inputStatus == "P" || inputStatus == "p")
        {
            // some code
        }
        else
        {
            System.out.println("I don't understand...");
        }
HelpNeeder
  • 6,383
  • 24
  • 91
  • 155

5 Answers5

4

Always use equals for string Comparison. & equalsIgnoreCase for case independent comparision

Also if one of the parameter is fixed string it should be used to compare like in your case F which avoid unnecessary null checks.

"F".equalsIgnoreCase(inputStatus)

Your code should look something like below.

   System.out.print("Employee's Last Name: ");
    String inputName = null;
    String inputStatus = null;
    if (scanner.hasNext())
        inputName = scanner.next();
    System.out.print("Employment Status (F or P): ");
    if (scanner.hasNext())
        inputStatus = scanner.next();

    if ("F".equalsIgnoreCase(inputStatus)) {
        // some code
    } else if ("P".equalsIgnoreCase(inputStatus)) {
        // some code
    } else {
        System.out.println("I don't understand...");
    }
Community
  • 1
  • 1
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
3

You should use equalsIgnoreCase() method.

if (inputStatus.equalsIgnoreCase("f"))
            {
                // some code
                System.out.println(inputStatus);
            }
swemon
  • 5,840
  • 4
  • 32
  • 54
1

You should use the strings equals() method.

Anne
  • 26,765
  • 9
  • 65
  • 71
meirrav
  • 761
  • 1
  • 9
  • 27
1

You cannot compare strings using == operator. This operator compares references. Use equals() method instead:

if ("F".equals(inputStatus) || "f".equals(inputStatus))

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

You can't compare Strings if "==", this basically compares the memory address of the two values, which will never match.

You should use something like...

if (inputStatus.equalsIgnoreCase("f")) 
{
    // Do something...
}

instead

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366