0

I'm trying to finish some code for my homework. But this line of code doesn't seem to work correctly for me. I want the user to only input the following string: freshman, sophomore, junior or senior. Any other input is invalid.

Don't know what else to try, I'm fairly new to java.

while (true) {
  System.out.println("Enter undergraduate level: ");
  lvl = inReader.nextLine();
  if (lvl != "freshman" || lvl != "sophomore" || lvl != "junior" || lvl != "senior") {
    System.out.println("Please enter valid level.");
  } else {
    break;
  }
}

I expected the input to only take freshman, sophomore, junior, and senior as in input, but it takes no inputs and only displays "Please enter valid level."

Lars Christian Jensen
  • 1,407
  • 1
  • 13
  • 14

1 Answers1

-1

Change all your '||' to '&&'

if (!"freshman".equals(lvl) && !"sophomore".equals(lvl) && !"junior".equals(lvl) && !"senior".equals(lvl)) {

But even better create a Set of valid strings and check if your input String is in the Set.

Set<String> validStrings = new HashSet<>();
validStrings.add("freshman");
validStrings.add("sophomore");
validStrings.add("junior");
validStrings.add("senior");
...
if(!validStrings.contains(lvl) {
       System.out.println("Please enter valid level.");
        }
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36