C# if 语句 != 到多个值

标签 c# if-statement statements

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/

相关文章:

javascript window.print() 无法打印完整的网格

c# - 如何确定图像是否包含使用特定颜色?

mysql - IF 条件不能正常工作

java - for 循环语法有什么问题?

jquery - If/else 语句 - 使 "else"与之前的状态相同

c# - 如何配置 Teamcitys SonarQube Runner 来分析 C# 文件

c# - 快速校验和散列?

java - 我无法获得更改 if 语句的按钮

java - 如何在 while-if 语句中使用单个变量遍历一组数字

c++ - While 循环在 C++ 中执行得太早