我对此非常努力。整数看起来很容易,但这是我一直试图在Visual Studio中用C#弄清楚的。
我希望用户输入一个像“a”这样的字母然后控制台写“apple”,b = bobby,c = charlie等等,当他们没有写信时,它会给出一条错误信息喜欢“没有使用的字母”。我不确定我是否想要从ToChar的字符串转换用户输入或者最好的方法是什么。我还没有进入数组,并没有想出带有字符的开关命令(而不是整数或字符串)。
这就是我尝试这样做的方式:
Console.WriteLine("Enter a letter ");
choice = Convert.ToChar(Console.ReadLine());
if (char choice = 'a'){
Console.WriteLine("apple");
}else if (char choice = 'b'{
Console.WriteLine("bobby");
}else if (char choice = 'b'{
Console.WriteLine("bobby");
}else (char choise=!IsLetter){
Console.WriteLine("No Letters entered");
答案 0 :(得分:2)
使用switch语句,可能最适合您的场景
static void Main(string[] args)
{
//initialise bool for loop
bool flag = false;
//While loop to loop Menu
while (!flag)
{
Console.WriteLine("Menu Selection");
Console.WriteLine("Press 'a' for apple");
Console.WriteLine("Press 'b' for bobby");
Console.WriteLine("Type 'exit' to exit");
//Read userinput
//Store inside string variable
string menuOption = Console.ReadLine();
switch (menuOption)
{
case "a":
//Clears console for improved readability
Console.Clear();
//"\n" Creates empty line after statement
Console.WriteLine("apple has been selected\n");
//Break out of switch
break;
case "b":
Console.Clear();
Console.WriteLine("bobby has been selected\n");
break;
case "exit":
Console.Clear();
Console.WriteLine("You will now exit the console");
//bool set to false to exit out of loop
flag = true;
break;
//Catch incorrect characters with default
default:
Console.Clear();
//Error message
Console.WriteLine("You have not selected an option\nPlease try again\n\n");
break;
}
}
Console.ReadLine();
答案 1 :(得分:2)
如果你想坚持下去,那么你可以做以下事情:
if (choice == 'a')
{
Console.WriteLine("apple");
}
else if (choice =='b')
{
Console.WriteLine("bobby");
}
else if (char choice = 'c')
{
Console.WriteLine("charlie");
}
else
{
Console.WriteLine("No Letters entered");
}
你不需要再把条件放在你的别人身上了:)
答案 2 :(得分:0)
这是您使用switch
编写的方式:
switch (choice){
case 'a':
Console.WriteLine("apple");
break;
case 'b':
Console.WriteLine("bobby");
break;
case 'c':
Console.WriteLine("charlie");
break;
default:
Console.WriteLine("No Letters entered");
break;
}