如果捕获到异常,请再次输入 [英] Input again if exception catched

查看:70
本文介绍了如果捕获到异常,请再次输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户重新输入,是否发现了异常,但不知道如何:

I want to ask user to re-input, if exception cathced, but don't know how:

class Quadrilateral
{
    Point[] pointsArr = new Point[4];

    public Quadrilateral()
    {
        foreach (Point pointVar in pointsArr)
        {

            try
            {
                Console.WriteLine("Input coordinates:");
                float x = float.Parse(Console.ReadLine());
                float y = float.Parse(Console.ReadLine());

                }
            catch (FormatException)
            {
                Console.WriteLine("Illegal value, please re-input");     
            }

        }
    }     
}

我考虑使用do-while循环,但是有一些问题.

I think of using do-while loop, but have some problems with it.

推荐答案

您可以使用普通的 while 循环并仅在没有异常的情况下递增迭代器变量,从而确保您获得所需的准确输入次数.如果发生任何异常,请使用 continue 关键字转到下一个迭代.

You can use a normal while loop and increment the iterator variable only if there is no exception, thereby ensuring that you get input the exact number of times that you want. Use continue keyword to go to the next iteration, if any exception occurs.

为简单起见,我使用了 Int 类型

I have used Int type for simplicity

        int[] pointsArr = new int[4];

        int arraySize = pointsArr.Length;
        int i = 0;
        while (i < arraySize)
        {
            try
            {
                Console.WriteLine("Input coordinates:");
                float x = float.Parse(Console.ReadLine());
                float y = float.Parse(Console.ReadLine());

            }
            catch (FormatException)
            {
                Console.WriteLine("Illegal value, please re-input");
                continue;
            }
            i++;
        }
        Console.ReadLine();

这篇关于如果捕获到异常,请再次输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆