gpt4 book ai didi

C# switch 语句字符串到字符错误

转载 作者:行者123 更新时间:2023-11-30 20:41:45 24 4
gpt4 key购买 nike

using System;
namespace prac4b
{
class prac4b
{
static void Main(string[] args)
{
int number1, number2, result;
char action;
string tempVal = "";
bool parseAttempt = false;

// ask for first number
Console.ReadLine();
Console.Write("Enter number > ");

//testing if integer with TryParse
tempVal = Console.ReadLine();
parseAttempt = Int32.TryParse(tempVal, out number1);

// if not a number
if (parseAttempt == false)
{
Console.WriteLine("You have not entered a number, application will now exit.");
Environment.Exit(0);
}
//if true, continue, ask for number2
if (parseAttempt == true)
{
//asking for number
Console.Write("Enter another number > ");
tempVal = Console.ReadLine(); //storing number temporailiy for checking
parseAttempt = Int32.TryParse(tempVal, out number2); //checking number2 if integer

//if not a number
if (parseAttempt == false)
{
Console.WriteLine("ERROR you have not entere a valid integer");
Environment.Exit(0);
}
//if true, continue, ask for action(+*-+)
Console.WriteLine("Action (*/+-) > ");
action = Console.ReadLine();

switch (action) //switch statement for action list
{
case "+":
Console.WriteLine("Result is > ", number1 + number2);
break;
case "-":
Console.WriteLine("Result is > ", number1 - number2);
break;
case "*":
Console.WriteLine("Result is > ", number1 * number2);
break;
case "/":
Console.WriteLine("Result is > ", number1 / number1);
break;
default:
Console.WriteLine("ERROR INVALID INPUT");
Environment.Exit(0);
break;
}
Console.WriteLine();
}
}
}
}

我试图让这个 switch 语句工作,但它不断出现错误,无法将字符串更改为字符。我没有看到我在哪里尝试将字符串更改为字符。

最佳答案

使用

action = Console.ReadKey().KeyChar;

而不是

action = Console.ReadLine();

&

大小写“+”:大小写“+”:

关于C# switch 语句字符串到字符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32087447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com