我是新来的C#开发,我想创建一个汽车控制台应用程序。我正在努力的部分是,我创建了一个列表,让用户输入汽车的价值,一旦用户完成,他/她应该能够点击输入以显示所添加的所有汽车的价值向上。转换字符串和整数的问题
下面是编译器错误:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.
下面是我在哪里得到的错误代码:
Console.Clear();
List<int> myCars = new List<int>();
Console.WriteLine("Enter the car into the lot");
int input = int.Parse(Console.ReadLine());
myCars.Add(input);
while (input.ToString() != "") //The != is not equal to
{
Console.WriteLine("Please enter another integer: ");
input = int.Parse(Console.ReadLine()); //This doesent work I dont know why
int value;
if (!int.TryParse(input.ToString(), out value))
{
Console.WriteLine("Something happened I dont know what happened you figure it out I dont want to");
}
else
{
myCars.Add(value);
}
}
if (input.ToString() == "Done")
{
int sum = 0;
foreach (int value in myCars)
{
sum += value;
Console.WriteLine("The total of all the cars on the lot are : " + " " + value.ToString());
}
Console.ReadLine();
}
https://dotnetfiddle.net/PYVofI这里是一个工作解。 – C1sc0
我解析了两次,因为它说输入无法转换为int。所以我必须将列表更改为字符串?或者我该如何改变readLine来读取int? –
从stdin开始,你只能读取字符串。所以你总是需要将字符串转换为int。 – C1sc0