简体   繁体   English

while 循环一个条件总是返回真?

[英]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.我试图用两个“ifs”做一个条件语句,当我输入正确的东西时它会起作用,但是当我输入不正确的口袋妖怪和正确的级别时它仍然有效。 I am pretty sure that one of the conditions in my while statement is always true (the first part).我很确定我的 while 语句中的一个条件始终为真(第一部分)。 Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment):下面是代码(抱歉格式化,只知道在Java环境下都是正确格式化的):

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. Pokeman 将永远不是 X 或不是 Y,这是基本逻辑,因为如果它是 X,那么 not-Y 就是真的。 If it's Y, then not-X is true.如果是 Y,则 not-X 为真。 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 )))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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