2017-10-31 10 views
-1

私はTryParseを使用する必要がありますが、私は実際にはわかりません。私は、ユーザーが任意の値を入力してプログラムがクラッシュするのを防ぐことができるようにしたい。Tryparseを動作させるにはどうすればよいですか?

string[] userInput = new string[5];    
bool isRunning = true; 
while (isRunning) 
{ 
    Console.WriteLine("[1]Lägg till ett föremål"); 
    Console.WriteLine("[2]Skriv ut innehållet"); 
    Console.WriteLine("[3]Sök i ryggsäcken"); 

    int menyVal = Convert.ToInt32(Console.ReadLine()); 

    switch (menyVal) 
    { 
     case 1: 
      Console.Write("Lägg till ett föremål: "); 
      userInput[0] = Console.ReadLine(); 
      Console.Write("Lägg till andra föremål: "); 
      userInput[1] = Console.ReadLine(); 
      Console.Write("Lägg till tredje föremål: "); 
      userInput[2] = Console.ReadLine(); 
      Console.Write("Lägg till fjärde föremål: "); 
      userInput[3] = Console.ReadLine(); 
      Console.Write("Lägg till femte föremål: "); 
      userInput[4] = Console.ReadLine(); 
      break; 

     case 2: 

      for (int i = 0; i < userInput.Length; i++) 
      { 
       Console.WriteLine(userInput[i]); 
      } 
      break; 

     case 3: 
        Console.Write("Skriv in sökOrd: "); 
      string sökOrd = Console.ReadLine(); 


      for (int i = 0; i < userInput.Length; i++) 
      { 
       if (userInput[i].ToUpper() == sökOrd.ToUpper()) 
       { 
        Console.WriteLine(userInput[i]); 
        break; 
       } 
      } 
      break; 

     case 4: 
      isRunning = false; 
      break; 
    } 
} 
Console.ReadLine();    
+1

'' int型menyVal。 int.TryParse(Console.ReadLine()、menyVal out); " –

+1

あなたのサンプルを英語に翻訳して、広いオーディエンスに質問が分かるようにしてください。そして、サンプルを短くすることができると思いますよね? –

+0

あなたのプログラムが番号を要求する場所に 'A'(または任意の非番号)を入力して、プログラムを試してみてください。それが壊れている場所を見てください。次にそれを修正しようとします。 –

答えて

0
次のコード行を使用してTryParseを使用して行うことができます

string Input= Console.ReadLine(); 
int menyVal = 0; 
int.TryParse(Input, out menyVal); 
+0

C#7(ビジュアルスタジオ2017)では、 'int.TryParse(Input、out int menyVal);'だけでもできます。前の行に変数を宣言する必要はありません。 –

+1

また、値が正常に解析されたかどうかを知るために、 'TryParse'の戻り値もチェックする必要があります。 –

+1

文字列入力= Console.ReadLine(); int値= 0; if(int.TryParse(入力、出力値)) { Console.WriteLine( "番号{0}"、値を入力します); } else { Console.WriteLine( "入力した値は数字ではありません"); } – derloopkat

関連する問題