初学者C#用户输入/转换/切换语句问题
我是一个初学者,我刚开始用C#编写一个简单的计算器程序,当我在终端上运行我的应用程序时,它的用户输入在我按enter键后仍然有ReadLine,如果我按两次enter键,这些代码就会被给出初学者C#用户输入/转换/切换语句问题,c#,switch-statement,user-input,calculator,C#,Switch Statement,User Input,Calculator,我是一个初学者,我刚开始用C#编写一个简单的计算器程序,当我在终端上运行我的应用程序时,它的用户输入在我按enter键后仍然有ReadLine,如果我按两次enter键,这些代码就会被给出 Unhandled exception. System.FormatException: Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(ParsingStatus sta
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Convert.ToInt32(String value)
这是我的密码
使用系统;
命名空间MyApplication
{
班级计划
{
静态void Main(字符串[]参数)
{
Console.WriteLine(“输入您的第一个号码”);
Console.ReadLine();
intx=Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“输入您的第二个号码”);
Console.ReadLine();
int y=Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“选择您的计算”);
Console.WriteLine(“类型+用于添加”);
Console.WriteLine(“类型-用于减法”);
Console.WriteLine(“类型*用于乘法”);
控制台写入线(“类型/用于分区”);
Console.ReadLine();
字符串表达式=Console.ReadLine();
开关(表达式)
{
格“+”:
控制台写入线(x+y);
打破
案例“-”:
控制台写入线(x-y);
打破
案例“*”:
控制台写入线(x*y);
打破
案例“/:
控制台写入线(x/y);
打破
}
}
}
}
因此,当您输入两次时,将调用nextReadLine
方法,并且该方法不是有效的整数值。因此,您应该始终检查该值是否可转换为整数。您可以使用int.TryParse
方法。您还可以使用try-catch块进行调试。您必须检查用户输入,它是有效的int还是空的
如果它不是一个有效的数字,您必须让它再次输入该数字
using System;
namespace MyApplication
{
public class Program
{
public void Main(string[] args)
{
FirstNumber:
Console.WriteLine("Enter Yor First Number");
string stringX = Console.ReadLine();
int x = 0;
if(String.IsNullOrWhiteSpace(stringX) || !int.TryParse(stringX, out x)){
goto FirstNumber;
}
SecondNumber:
Console.WriteLine("Enter Yor Second Number");
string stringY = Console.ReadLine();
int y = 0;
if(String.IsNullOrWhiteSpace(stringY) || !int.TryParse(stringY, out y)){
goto SecondNumber;
}
Expression:
Console.WriteLine("Choose your calculation");
Console.WriteLine("Type + for Addition");
Console.WriteLine("Type - for Subtraction");
Console.WriteLine("Type * for Multiplication");
Console.WriteLine("Type / for Division");
string expression = Console.ReadLine();
if(expression!="+" && expression!="-" && expression!="/" && expression!="*"){
goto Expression;
}
switch(expression)
{
case "+":
Console.WriteLine(x+y);
break;
case "-":
Console.WriteLine(x-y);
break;
case "*":
Console.WriteLine(x*y);
break;
case "/":
Console.WriteLine(x/y);
break;
}
}
}
}
非常感谢你的问题solved@KennethCho祝你玩得愉快