0
String parkingStringChoice;
System.out.println("Would you like to purchase parking? (Y or N)");
parkingStringChoice = scnr.nextLine();
int parkingChoice;

switch(parkingStringChoice) {
    case "Y":
        System.out.println("You have parking");
        parkingChoice = 1;
        break;
    case "N":
        System.out.println("You dont have parking");
        parkingChoice = 0;
        break;

}

if (parkingStringChoice != "Y" && parkingStringChoice != "N") {
    System.out.println("Reenter valid input.");
    System.exit(0);
}

The above portion is my code for a portion of my program asking if the user wants parking or not. I am trying to write an if statement to make sure if the user does not input Y or N it will print an error and then exit.

Instead of this, it is currently executing the if statement at all times, whether Y, N, or some other string is entered. Any help is appreciated, thanks.

Conhair
  • 31
  • 1
  • 6
  • Check your assumptions—conditionals in Java are pretty well vetted. – Dave Newton Jan 31 '20 at 01:22
  • 1
    The `if` statement is executing because the condition **is** true. That is what `if` does. Your question should be "why is this condition true"? – kaya3 Jan 31 '20 at 01:23
  • Because when you read a line, it gets special values after your input (\r, \n, etc). NOTE: Be sure you compare UPPERCASE and/or lowercase. – Ivan Verges Jan 31 '20 at 01:24
  • why don't you instead use the `default` case in the switch block? – jsotola Jan 31 '20 at 01:25
  • Apply De Morgan's theorem and your `if (parkingStringChoice != "Y" && parkingStringChoice != "N")` becomes `if !(parkingStringChoice == "Y" || parkingStringChoice == "N")`, see linked duplicate for why **that** is always `true`. – Elliott Frisch Jan 31 '20 at 01:25

0 Answers0