如何在此处删除“转到”

时间:2015-06-18 10:33:33

标签: c#

我已经读过,建议不要在C#中使用“goto” 但是,我的代码使用goto,到目前为止,在尝试避免“goto”时出现错误

anum1r:
Console.Write ("What is the first number? ");
try {
    num1 = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
    Console.Beep ();
    Console.WriteLine ("");
    Console.WriteLine ("You have entered an invalid number!");
    Console.WriteLine ("");
    goto anum1r;
}
anum2r:
Console.Write ("What is the second number? ");
try {
    num2 = Convert.ToDouble (Console.ReadLine ());
} catch (System.FormatException) {
    Console.Beep ();
    Console.WriteLine ("");
    Console.WriteLine ("You have entered an invalid number!");
    Console.WriteLine ("");
    goto anum2r;
}
answer = num1 + num2;

如何在不使用GOTO的情况下转换此代码。 TY

8 个答案:

答案 0 :(得分:2)

使用while循环:

double num1;
while (true) {
    Console.Write ("What is the first number? ");
    try {
        num1 = Convert.ToDouble (Console.ReadLine ());
        break;
    } catch (System.FormatException) {
        Console.Beep ();
        Console.WriteLine ("");
        Console.WriteLine ("You have entered an invalid number!");
        Console.WriteLine ("");
    }
}

由于您需要两次此代码,因此在一个单独的方法(如@James的答案)中重构它也是一个好主意。 (虽然它需要一个额外的参数来修改用户提示。)

答案 1 :(得分:0)

您可以使用PATH循环

while

答案 2 :(得分:0)

您可以使用for - 循环和double[]之类的集合,也可以使用double.TryParse

int numbers = 10;
double[] allNumbers = new double[numbers];
for (int i = 0; i < numbers; i++)
{
    Console.Write("What is the {0}. number? ", i + 1);
    double num;
    if (double.TryParse(Console.ReadLine().Trim(), out num))
    {
        allNumbers[i] = num;
    }
    else
    {
        i--; // ask the user until we have the numbers
        Console.Beep();
        Console.WriteLine("");
        Console.WriteLine("You have entered an invalid number!");
        Console.WriteLine("");
    }
}
double answer = allNumbers.Sum(); // LINQ so add using System.Linq;

另一种方法是为此目的提取方法:

private static double? ReadNumberFromConsole()
{
    double num;
    if (double.TryParse(Console.ReadLine().Trim(), out num))
        return num;
    else
        return null;
}

这使代码更具可读性:

for (int i = 0; i < numbers; i++)
{
    Console.Write("What is the {0}. number? ", i + 1);
    double? num = ReadNumberFromConsole();
    if (num.HasValue)
    {
        allNumbers[i] = num.Value;
    }
    else
    {
        i--; // ask the user until we have the numbers
        Console.Beep();
        Console.WriteLine("");
        Console.WriteLine("You have entered an invalid number!");
        Console.WriteLine("");
    }
}

答案 3 :(得分:0)

MAY 只需使用循环:

double PromptForNumber(string message) {
    while (true) {
        Console.Write(message + " ");
        try {
            return Convert.ToDouble(Console.ReadLine());
        } catch (FormatException) {
            Console.Beep();
            Console.WriteLine();
            Console.WriteLine("You have entered an invalid number!");
            Console.WriteLine();
        }
    }
}

用作:

double num1 = PromptForNumber("What is the first number?");
double num2 = PromptForNumber("What is the second number?");

但是在这里您还使用了他们不需要的例外情况。 无效的用户输入并不例外,有更好的方法可以解决这个问题:

double PromptForNumber(string message) {
    while (true) {
        Console.Write(message + " ");

        double number;
        if (Double.TryParse(Console.ReadLine(), out number))
            return number;

        Console.Beep();
        Console.WriteLine("\nYou have entered an invalid number!\n");
    }
}

请注意,这样您还可以处理原始代码中遗漏的OverflowException

您需要100个输入吗?一行代码:

var inputs = Enumerable.Range(1, 100)
    .Select(x => PromptForNumber(String.Format("Enter number #{0}:", x)));

答案 4 :(得分:0)

有两种改善代码的好方法:

  1. 将用于重复询问用户输入数字的逻辑提取到单独的方法中,直到他们输入有效数字。 (使用循环结构来处理循环而不是goto。)
  2. 使用double.TryParse()以避免必须捕获格式异常。
  3. 如果你把它们放在一起,你会得到类似这样的代码:

    using System;
    
    namespace Demo
    {
        public static class Program
        {
            private static void Main()
            {
                double first = askForNumber("What is the first number? ");
                Console.WriteLine();
                double second = askForNumber("What is the second number? ");
    
                Console.WriteLine("\nYou entered {0} and {1}", first, second);
            }
    
            private static double askForNumber(string prompt)
            {
                while (true)
                {
                    Console.Write(prompt);
                    double result;
    
                    if (double.TryParse(Console.ReadLine(), out result))
                        return result;
    
                    Console.Beep();
                    Console.WriteLine("\nYou have entered an invalid number!\n");
                }
            }
        }
    }
    

答案 5 :(得分:0)

我强烈建议避免在用户输入上使用Convert.ToDouble。 在每个级别上使用异常作为输入验证系统都是错误的。

使用类似的东西:

double GetNumberFromUser() {
    double Num = double.NaN;
    while(!double.tryParse(Console.ReadLine(), out Num) && !double.IsNaN(Num))
    {
        Console.Beep();
        Console.WriteLine("");
        Console.WriteLine("You have entered an invalid number!");
        Console.WriteLine("");
    }
    return Num;
}

为什么还测试IsNaN? read this.

答案 6 :(得分:-1)

private Double InputNum1
{
    Console.Write ("What is the first number? ");
    try 
    {
        num1 = Convert.ToDouble (Console.ReadLine ());
        return num1;
    } 
    catch (System.FormatException) 
    {
        Console.Beep ();
        Console.WriteLine ("");
        Console.WriteLine ("You have entered an invalid number!");
        Console.WriteLine ("");
        InputNum1();
    }
}

答案 7 :(得分:-2)

您可以使用一段时间查询数字,直到它们有效:

double? num1 = null;
while (num1==null){
   Console.Write ("What is the first number? ");
   try {
       num1 = Convert.ToDouble (Console.ReadLine ());
   } catch (System.FormatException) {
       Console.Beep ();
       Console.WriteLine ("");
       Console.WriteLine ("You have entered an invalid number!");
       Console.WriteLine ("");
   }
}