gpt4 book ai didi

java - 为什么这个 if 语句会在这个 While 循环中触发?

转载 作者:行者123 更新时间:2023-12-01 17:19:41 25 4
gpt4 key购买 nike

我是 Java 新手,我正在创建一个 while 循环,条件之一是:

if ((userChoice != 'p') || (userChoice != 'P') || (userChoice != 's') || (userChoice != 'S'))
System.out.println("***请使用P或S。***");

为什么当我输入“p”、“P”、“s”或“S”时,程序仍然输出“”*请使用P或S。 *“?”

这是整个程序:

import java.util.Scanner;

public class Foothill
{
public static void main(String[] args)
{
// declare an object that can be used for console input
Scanner inputStream = new Scanner(System.in);

// declare variables
String strUserInput;
char userChoice, userCredits;
int numYogurts, yogurtWallet = 0;
// while loop for full transaction
while (true)
{
// menu message
System.out.println("Menu: \n P (process Purchase) \n S (Shut down)");
strUserInput = inputStream.nextLine();
userChoice = strUserInput.charAt(0);

// condition that forces users to select only P or S
if ((userChoice != 'p') || (userChoice != 'P') || (userChoice != 's') || (userChoice != 'S'))
System.out.println("*** Use P or S, please. ***");

System.out.println("Your choice:" + userChoice);
// if condition that starts purchase part of transaction
if ( (userChoice == 'p') || (userChoice == 'P') )
{
System.out.println("How many yogurts would you like to buy?");
strUserInput = inputStream.nextLine();
numYogurts = Integer.parseInt(strUserInput);

yogurtWallet += numYogurts;

System.out.println("You just earned " + numYogurts + " stamps and have a total of " + yogurtWallet + " to use");
// if condition that tests number of purchased yogurts
if (yogurtWallet >= 10)
{
System.out.println("You qualify for a free yogurt. Would you like to use your credits? (Y or N)");
strUserInput = inputStream.nextLine();
userCredits = strUserInput.charAt(0);

if ((userCredits == 'Y') || (userCredits == 'y'))
{
yogurtWallet -= 10;
System.out.println("You have just used 10 credits and have " + yogurtWallet + " left. Enjoy your free yogurt.");
}
}
}
// if condition that stops the program
if ( (userChoice == 's') || (userChoice == 'S') )
{
System.out.println("Goodbye!");
break;
}

}
}
}

最佳答案

假设您输入了p。由于Short Circuit Evaluation ,Java会继续检查if语句内的所有条件,接下来检查的是!= 'P',即true!对于其他输入也是如此:

userChoice |  != 'p' | != 'P' | != 's' | != 'S'
-----------+---------+--------+--------+-------
p | Yes | -- | -- | --
P | No | Yes | -- | --
s | No | No | Yes | --
S | No | No | No | Yes

-- 表示未评估,因为 Short Circuit Evaluation .

所以在所有情况下,您的 if 都满足!

关于java - 为什么这个 if 语句会在这个 While 循环中触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com