[英]Why is this if-statement triggering in this While-loop?
我是Java的新手,我正在創建一個while循環,其條件之一是:
if ((userChoice != 'p') || (userChoice != 'P') || (userChoice != 's') || (userChoice != 'S')) System.out.println("*** Use P or S, please. ***");
為什么當我輸入“ 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;
}
}
}
}
無論您選擇哪個字母,它都將不等於其他選擇。 || 表示“或”。 因此,在A OR B中,如果A為true或B為true,則整個條件為true。 您需要做的是對&使用&&。
使用if ((userChoice != 'p') && (userChoice != 'P') && (userChoice != 's') && (userChoice != 'S'))
這樣可以解決您的問題。
if ((userChoice != 'p') && (userChoice != 'P') &&
userChoice != 's') && (userChoice != 'S'))
System.out.println("*** Use P or S, please. ***");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.