为什么 Java 在 while 循环中跳过我的第二个条件?

Why is Java skipping my second condition in the while loop?

有谁知道为什么 Java 会跳过第一个条件?

while((withdraw % 100) != 0 && (withdraw > startBalance))

虽然我说提款必须小于startBalance,但您仍然可以输入大于startBalance的数字,并且newBalance将为负数。

这是我的代码:

public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  int startBalance = 1000;
  System.out.println("Please enter how much you want to withdraw: ");
  int withdraw = input.nextInt();

  while((withdraw % 100) != 0 && (withdraw > startBalance)){
    System.out.println("Sorry, you can only withdraw a value multiple of 100 (we only have 100 SEK bills): ");
    withdraw = input.nextInt();
  }

  int newBalance = startBalance-withdraw;
  System.out.println("Thanks! Your new balance is: SEK " + newBalance);
}

如果第一个条件为假,则不会考虑第二个条件。如果第一个条件为真,那么它还将评估第二个条件。这是因为您正在使用 && 操作。如果你使用 ||然后如果第一个为假,它将评估下一个条件。

试试这个代码:

import java.util.Scanner;

public class Balance {

    public static void main(String[] args) {

          Scanner input = new Scanner(System.in);
          int startBalance = 1000;
          System.out.println("Please enter how much you want to withdraw: ");
          int withdraw = input.nextInt();

          while((withdraw % 100) != 0 || (withdraw > startBalance)){
            System.out.println("Sorry, you can only withdraw a value multiple of 100 (we only have 100 SEK bills): ");
            withdraw = input.nextInt();
          }

          int newBalance = startBalance-withdraw;
          System.out.println("Thanks! Your new balance is: SEK " + newBalance);
        }
}

我用过

|| (or)

而不是

&& (and)

因为我们总是需要检查用户是否有足够的余额:)

while((withdraw % 100) != 0 && (withdraw > startBalance))

让我用简单的文字读出你的病情:

"只要满足两个条件就继续循环:

  • 请求的金额不完整;
  • 大于起始余额。

那么,假设我们请求 1,000,000。是"not round"吗?不,这两个条件都成立吗?没有。因此,循环结束。

附带一点,这与&&&的区别或求值顺序无关。这只是简单的常识性逻辑。

我的假设是您不希望循环检查 100 的模 % 是否不等于 AND 取款是否大于起始余额。

双符号 && 检查两个参数是否为真,除非您的起始余额小于 0,否则永远不会满足 while 循环的条件。

因此,您想使用 or 运算符 || 来检查是否满足您正在寻找的一个或另一个条件。

变化:while((withdraw % 100) != 0 && (withdraw > startBalance))

收件人:while((withdraw % 100) != 0 || (withdraw > startBalance))

这将解决您的问题。