Console.Clear();
string choice;
Console.WriteLine("Welcome to Costa coffee\n");
Console.WriteLine("1:> Latte\n2:> Cappuccino\n3:> Espresso\n4:> Double espresso");
Console.WriteLine("\nPlease select a coffee by pressing 1-4");
choice = Console.ReadLine();
if (choice == "1")
{
Console.WriteLine("\nYou have selected: latte");
}
if (choice == "2")
{
Console.WriteLine("\nYou have selected: Cappuccino");
}
if (choice == "3")
{
Console.WriteLine("\nYou have selected: Espresso");
}
if (choice == "4")
{
Console.WriteLine("\nYou have selected: Double espresso");
}
else if (choice !="1" || choice !="2" || choice !="3" || choice !="4")
{
Console.WriteLine("Incorrect value, please try again");
}
我正在尝试制作程序,以便如果选择不等于 1、2、3、4,那么它会显示“不正确的值,请重试”,但是当我随机按任何东西时它仍然有效但仍然显示当我按 1、2、3 或 4 时出现此错误消息。有什么想法吗?
最佳答案
在这种情况下推荐switch
:
var myConsoleString = "";
switch (choice)
{
case "1": myConsoleString = "\nYou have selected: latte"; break;
case "2": myConsoleString = "\nYou have selected: Cappuccino"; break;
case "3": myConsoleString = "\nYou have selected: Espresso"; break;
case "4": myConsoleString = "\nYou have selected: Double espresso"; break;
default: myConsoleString = "\nIncorrect value, please try again"; break;
}
Console.WriteLine(myConsoleString);
关于C# if 语句 != 到多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42637067/