c# - 如何返回到for循环的开始?

标签 c#

我正在处理下面描述的问题,我正在使用循环来解决它。我还没去上课。如果输入的数据不正确,我需要重新启动循环。

在 If 语句中,

if (isInteger == false) 

我可以使用 break 语句来转义,但是 for 循环的其余部分将执行并且它会重新启动并递增到 i = 1。如果数据类型错误,我需要它返回到开始循环,其中 i= 0。我该怎么做?

挑战:编写一个程序,从用户那里读取 5 个整数并打印它们的总和。如果输入的号码无效,程序应提示用户输入另一个号码。

Console.WriteLine("This program accepts 5 integers from the user and returns their sum.\nIf an invalid integer is entered, the program notifies the user and asks for correct input.");

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Please enter Integer {0} now.", (i + 1));
            string rawInput = Console.ReadLine();

            int integerSum = 0;

            int integerInput;
            bool isInteger = int.TryParse(rawInput, out integerInput);

            if (isInteger == false)
            {
                Console.WriteLine("This is not a valid integer. Please enter a valid integer now:");
                break;
            }
            else
            {                   
                integerSum += integerInput;                   
            }
        }

最佳答案

像这样继续使用

if (isInteger == false)
{
   Console.WriteLine("This is not a valid integer. Please enter a valid integer now:");
   i--;
   continue;
}

关于c# - 如何返回到for循环的开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417204/

相关文章:

c# - 当我需要抓取网站时,我应该使用 BackgroundWorker 还是 Threads?

c# - 重命名可序列化类

c# - 工具提示不会显示第二次创建表单

c# - 如何在 Asp.net Core 运行时从 DependencyInjection 解析泛型类型服务

c# - 此平台不支持 LocalDB

c# - 如何在 C# 中编写 SNMP 代理或 SNMP 扩展代理 DLL

c# - 计算一个月中的星期一数

c# - 从 C# 通用字典中过滤掉值

c# - 如何为我的场景替换 if 循环逻辑?

c# - ResetBindings() 不更新 BindingSource