タイトルは私がそこに欲しいものを得ることに関してちょっと面倒です。c# - コンソールアプリケーション - ユーザーが何も入力せずにEnterキーを押したときのエラーを解決する
string _val = Console.ReadLine();
tempScoreToWin = Convert.ToInt32(_val);
ユーザAを押すと、エラーが発生します値を入力せずに入力して、アプリケーションが終了するとき、私が知りたいことは次のとおりです。
基本的に私はint型に私の文字列を変換しました。
どうすればこの問題を回避できますか?
while (true)
{ //This will allow the player to manually change the score.
//------------------------------------------------------------------------------------------
string _val = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
//-----------------------------------------------------------------
tempScoreToWin = Convert.ToInt32(_val); // Converting the users input (Console.ReadLine()) into an integer.
if (tempScoreToWin > 0) // If the users input is higher than zero ...
{
scoreToWin = tempScoreToWin; // Reset the scoreToWin variable with the value of tempScoreToWin.
Console.WriteLine("The score has been set to {0}.", scoreToWin); // Let the user know that the score has been changed successfully.
break; // Break out of the while loop.
}
else
{ // If the player has not put a correct integer in ...
Console.WriteLine("The score has been set at a default of {0}.", scoreToWin); // then the score will be set to the default value of scoreToWin
break; // Break out of the while loop.
}
}
Console.ReadLine();
Console.Clear();
//-----------------------------------------------------------------
乾杯:
は、ここに私の完全なコードです!
'Int32.TryParse'メソッドを見てください。 –
代わりに何をしたいですか? – Chris
また、エディタで '{}'のようなボタンがあり、ポストのセクションをコードとしてマークすることができます。私はコードブロックを編集してそれらを修正したいと思いますが、あなたは現時点であなたの投稿を積極的に編集しているように見えますので、間違って変更を失いたくはありません。 – Chris