1

我想做的是使用 try-catch 异常重新启动程序并让用户再次重新输入数据值。我该怎么做?我尝试使用 goto 将其带回第一行,但这似乎不起作用。(普遍的共识是 goto 是邪恶的)。非常感谢任何可以提供的帮助。

Console.WriteLine("Please enter the two points that you wish to know the distance between:");
string point = Console.ReadLine();
string[] pointInput = point.Split(' ');


int pointNumber = Convert.ToInt16(pointInput[0]);                        //Stores the actual input number's into two integers
int pointNumber2 = Convert.ToInt16(pointInput[1]);

try                                                                      //Try-Catch statement to make sure that the User enters relevant PointNumbers
{
    double latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
    double longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
    double elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

    double latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
    double longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
    double elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // Uses the relationship between the pointnumber and the array to select the required items from the array.


    //Calculate the distance between two point using the Distance class
    Console.WriteLine("The distance in km's to two decimal places is:");
    Distance curDistance = new Distance(latitude, longtitude, elevation, latitude2, longtitude2, elevation2);
    Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");
}
catch(IndexOutOfRangeException)
{

    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers");

  // here is where I would have the program restart  

}
4

8 回答 8

3

当您开始学习编程时,您会了解到这些情况可以使用 while 或 do-while 循环来解决。因此,我会给你这样的答案:

            bool restart = false;
            do
            {
                restart = false;
                Console.WriteLine("Please enter the two points that you wish to know the distance between:");
                string point = Console.ReadLine();
                string[] pointInput = point.Split(' ');


                int pointNumber = Convert.ToInt16(pointInput[0]);                        //Stores the actual input number's into two integers
                int pointNumber2 = Convert.ToInt16(pointInput[1]);

                try                                                                      //Try-Catch statement to make sure that the User enters relevant PointNumbers
                {
                    double latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
                    double longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
                    double elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

                    double latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
                    double longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
                    double elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // Uses the relationship between the pointnumber and the array to select the required items from the array.


                    //Calculate the distance between two point using the Distance class
                    Console.WriteLine("The distance in km's to two decimal places is:");
                    Distance curDistance = new Distance(latitude, longtitude, elevation, latitude2, longtitude2, elevation2);
                    Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");
                }
                catch (IndexOutOfRangeException)
                {

                    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers");
                    restart = true;
                }
            } while (restart);

请注意,如果您在 Main 中调用 Main 您最终可能会导致 StackOverflowException :-D

于 2012-10-27T11:38:01.833 回答
1

只要它是一个控制台应用程序,您就可以在块中调用Main方法。catch

private static int m_NumberOfRetries = 5; //Define how many times application can "restart" itself to avoid stackoverflow. 

static void Main(string[] args)
{
    try
    {
        //Do something useful
    }
    catch
    {
        m_NumberOfRetries--;
        if (m_NumberOfRetries != 0)
        {
            Main(args);
        }
    }
 }

但这不是一个好习惯。您可以通过检查应用程序中的用户输入来避免这种情况。

于 2012-10-27T11:21:25.683 回答
1

您应该考虑在始终对其进行操作之前验证您的输入。考虑创建一个专门的方法来接受用户输入并对其进行验证。该方法可以在内部继续请求用户输入,直到验证成功。

于 2012-10-27T11:23:50.520 回答
0
// Starts a new instance of the program itself
System.Diagnostics.Process.Start(Application.ExecutablePath);

// Closes the current process
Environment.Exit(0);
于 2012-10-27T11:27:05.547 回答
0

考虑只重新开始读取输入。如果这是您需要的,以下将是合适的:

将方法 getData() 放在 Distance 类中。Distance 类必须有一个非参数构造函数。

距离.java

private double latitude;
private double longitude;
private double elevation;
private double latitude2;
private double longitude2;
private double elevation2;

public Distance() {}

public boolean getData(){
    Console.WriteLine("Please enter the two points that you wish to know the distance between:");
    string point = Console.ReadLine();
    string[] pointInput = point.Split(' ');
    int pointNumber = Convert.ToInt16(pointInput[0]);
    int pointNumber2 = Convert.ToInt16(pointInput[1]);
    try{
        latitude = (Convert.ToDouble(items[pointNumber * 3]));            //
        longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));    //
        elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));     //

        latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));          //
        longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));  //
        elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));   // I assume the exception goes from these 6 lines               

        return true;
    } catch (IndexOutOfRangeException) {
        return false;
    }
}

主.java:

Distance curDistance = new Distance();
while(!curDistance.getData()) 
    Console.WriteLine("You have selected a point number outside the range of the data entered, please select two new pointnumbers"); 
Console.WriteLine("The distance in km's to two decimal places is:");   
Console.WriteLine(String.Format("{0:0.00}", curDistance.toDistance()) + "km");

只要输入不正确,while 循环就会使程序要求输入。

于 2012-10-27T11:29:11.207 回答
0
catch()
{
  console.writeline("Some error");
  private void restart()
   {
    //write Press any key to restart the program 

   //clear the screen;

  //call the main method; 
  }
}
于 2012-10-27T11:30:06.730 回答
0

用户数据输入问题和程序执行异常有很大的不同,你应该有两个独立的机制来处理每个问题。

用户数据输入问题(例如,用户在需要数字的地方输入“abc”)应由输入验证机制(由您编写)处理。此类问题可由用户纠正,通常会向用户显示验证失败的原因,并给予重新输入数据的机会。

用户无法纠正程序执行异常(例如,尝试连接数据库时发生超时),应使用语言中内置的 try/catch 机制进行处理。

由于多种原因,使用 try/catch 机制来提供程序流控制(这是您正在尝试做的事情)被认为是糟糕的编程实践。

于 2012-10-27T13:08:52.470 回答
0

对于任何正在寻找通用方法的人,通过合并LeriNikola Davidovic的答案,我想出了一个不使用重复且更简洁的模板。

int numberOfRetriesLeft = 5;
bool shouldRetry = false;

do
{
    shouldRetry = false;
    
    try
    {
        // call the method that needs to support retrying
    }
    catch
    {
        shouldRetry = true;
        numberOfRetriesLeft--;
        // log error
    }
}
while (shouldRetry && numberOfRetriesLeft > 0);

它可以被进一步重构为一个接受Func作为参数的包装方法,但这对于一个例子来说更简洁。

于 2021-08-12T07:36:06.530 回答