c#如何创建一个打开的while循环,当用户需要时停止

本文关键字:循环 用户 while 创建 何创建 一个 | 更新日期: 2023-09-27 18:13:57

我正在用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++;
        }
    }

我知道这个代码是不正确的

c#如何创建一个打开的while循环,当用户需要时停止

如果用户输入的不是整数,则可以将goon设置为" "以外的其他值。

检查是否输入了整数的最简单方法是使用Int32。TryParse方法。

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";
        }
    }
}
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;
        }
    }
}

我已经更新了你的方法,假设"quit"文本作为用户的退出信号来打破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++;
        }
    }