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,029
  • 1
  • 8
  • 13

2 Answers2

-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
  • 5,975
  • 1
  • 17
  • 34
-1

I suggest to use a proper IDE. Most IDEs show you that you made a mistake by trying to compare two Strings without equals.

Background: Java stores a String as an array of characters. If you compare two Strings with the "==" the location of the char-arrays are compared and not the content of them.

So you should call string.equals(otherString) as this compares the content of the underlying arrays. If the characters in each place of the array match the .equals() evaluates to true, otherwise false.

Marco Zielbauer
  • 433
  • 1
  • 6
  • 16