简体   繁体   中英

While loop one condition always returning true?

I am trying to make a conditional statement with two "ifs", and it works when I input the correct thing, but when I input an incorrect pokemon and a correct level it still works. I am pretty sure that one of the conditions in my while statement is always true (the first part). Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment):

while ((!(Pokemon.equalsIgnoreCase(Pikachu)) || !(Pokemon.equalsIgnoreCase(Charmander)) || !(Pokemon.equalsIgnoreCase(Squirtle)) || !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) {

  System.out.println();
  System.out.println("Which one would you like? What level should it be?\n1 to 15 would be best, I think.");
  Pokemon = sc.next();
  Level = sc.nextInt();

  if ((Level <= 15) && (Level >= 1)) {
    if ((Pokemon.equalsIgnoreCase(Pikachu)) || (Pokemon.equalsIgnoreCase(Charmander)) || (Pokemon.equalsIgnoreCase(Squirtle)) || (Pokemon.equalsIgnoreCase(Bulbasaur))) {
                System.out.print("Added level " + Level + " " + Pokemon + " for " + Trainer + ".");
    }
    else {
      System.out.println("Invalid Pokemon!");
    }
  }
  else {
    System.out.println("Invalid Level!");
  }
}

Pokeman will always be either not X or not Y, it's basic logic since if it's X, then not-Y is true. If it's Y, then not-X is true. If it's neither then both will be true.

Change || to && and think through your logic on paper.

Should be:

    while ((!(Pokemon.equalsIgnoreCase(Pikachu)) && 
!(Pokemon.equalsIgnoreCase(Charmander)) && 
!(Pokemon.equalsIgnoreCase(Squirtle)) && 
!(Pokemon.equalsIgnoreCase(Bulbasaur))) && 
!((Level <= 15)&&(Level >= 1 )))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM