2016-11-28 7 views
0

私はC#を開発するのが初めてで、カーコンソールアプリケーションを作成しようとしています。私が苦労している部分は、ユーザーが車の価値を入力できるようにするためのリストを作成しています。ユーザーが完了すると、入力したすべての車の値を表示するだけでよいアップ。ここで文字列とintの変換に関する問題

は、コンパイラからのエラーです:ここでは

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失敗した作業である場合にはfalseを返しますInt32.TryParseを()を使用する必要があります溶液。 – C1sc0

+0

私は入力をintに変換できないと言っていたので、2回解析しました。だから私は文字列にリストを変更する必要がありますか?またはreadLineをint型に変更するにはどうすればよいですか? –

+0

stdinから、文字列だけを読むことができます。したがって、常にstringを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(); 
0

でInt32.Parse()メソッドは、使用しますが、例えば整数ではない値を解析しようとする場合に、FormatExceptionがスローされます。ここでは修正されたコードです文字列(あなたの場合は「完了」) https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx

あなたはあなたの構文解析がここ https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx

+0

@ジョイあなたは正しい、私の間違い – jambonick

関連する問題