尝试做一个简单的用户输入到字符输出控制台程序
本文关键字:输入 用户 字符 输出 程序 控制台 简单 一个 | 更新日期: 2023-09-27 18:13:43
我仔细看了一下。整数似乎很容易,但这是我一直试图在visual studio中的c#中弄清楚的。
我想让用户输入像"a"这样的字母,然后控制台写"apple",b=bobby, c=charlie等,当他们没有输入字母时,它会给出一个错误消息,如"没有使用字母"。我不确定是否应该将用户输入从ToChar字符串转换为ToChar,或者这样做的最佳方法是什么。我还没有接触到数组,也没有弄清楚使用字符(而不是整数或字符串)的switch命令。
我是这样做的:
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");
如果你想坚持If else,你可以这样做:
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");
}
你不需要再给else加上条件了:)
使用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();
使用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;
}