2016-11-28 36 views
0

我是新來的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(); 
} 
+0

https://dotnetfiddle.net/PYVofI這裏是一個工作解。 – C1sc0

+0

我解析了兩次,因爲它說輸入無法轉換爲int。所以我必須將列表更改爲字符串?或者我該如何改變readLine來讀取int? –

+0

從stdin開始,你只能讀取字符串。所以你總是需要將字符串轉換爲int。 – C1sc0

回答

0

這個錯誤是因爲「完成」不能被解析整數。 你也有一些語義錯誤。這裏的校正代碼:

 Console.Clear(); 
     List<int> myCars = new List<int>(); 

     Console.WriteLine("Enter the car into the lot"); 
     string input = Console.ReadLine(); 
     int IntValue; 
     if (int.TryParse(input, out IntValue)) 
     { 
      myCars.Add(IntValue); 
     } 

     while (input != "Done") //The != is not equal to 
     { 
      Console.WriteLine("Please enter another integer: "); 
      input = Console.ReadLine(); 

      if (int.TryParse(input, out IntValue)) 
      { 
       myCars.Add(IntValue); 
      } 

     } 

     int sum = 0; 
     foreach (int value in myCars) 
     { 
      sum += value; 
     } 
     Console.WriteLine("The total of all the cars on the lot are : " + " " + sum.ToString()); 
     Console.ReadLine();