我在C#中编写了一个小循环,我希望在用户指定之前保持打开状态。
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
while (goon == " ")
{
Console.WriteLine("Enter a score");
score += int.Parse(Console.ReadLine());
Console.WriteLine(score + " " + counter);
counter++;
}
}
我知道这段代码不正确。
答案 0 :(得分:1)
如果用户输入了除整数之外的任何内容,则可以将goon
设置为" "
以外的其他内容。
检查是否输入了整数的最简单方法是使用Int32.TryParse method。
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
int userInput = 0;
bool isInt = true;
while (goon == " ")
{
Console.WriteLine("Enter a score");
isInt = Int32.TryParse(Console.ReadLine(), out userInput);
if(isInt)
{
score += userInput;
Console.WriteLine(score + " " + counter);
counter++;
}
else
{
goon = "exit";
}
}
}
答案 1 :(得分:0)
public void ScoreCalc()
{
int counter = 1;
int score = 0;
String input;
while (true)
{
Console.WriteLine("Enter a score");
input=Console.ReadLine();
if(input != "end"){
score += int.Parse(input);
Console.WriteLine(score + " " + counter);
counter++;
}else{
break;
}
}
}
答案 2 :(得分:0)
我已经更新了您的方法,假设"退出"文本作为来自用户的退出信号以打破while循环。希望这有帮助!
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
var userInput = string.Empty;
var inputNumber = 0;
const string exitValue = "quit";
while (goon == " ")
{
Console.WriteLine("Enter a score or type quit to exit.");
userInput = Console.ReadLine();
if (userInput.ToLower() == exitValue)
{
break;
}
score += int.TryParse(userInput, out inputNumber) ? inputNumber : 0;
Console.WriteLine(score + " " + counter);
counter++;
}
}