while循环中的try-catch方法? [英] A try-catch method in while loop?

查看:706
本文介绍了while循环中的try-catch方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,我想把try-catch放在while循环中。逻辑是,当存在输入错误时,程序将继续要求正确的输入。我该怎么做?在此先感谢。

I have this code, and I want to put the try-catch inside a while loop. The logic would be, "while there is an input error, the program would keep on asking for a correct input". How will I do that? Thanks in advance.

public class Random1 {

  public static void main(String[] args) {

    int g;

    Scanner input = new Scanner(System.in);
    Random r = new Random();
    int a = r.nextInt(10) + 1;


    try {
        System.out.print("Enter your guess: ");
        g = input.nextInt();
        if (g == a) {

            System.out.println("**************");
            System.out.println("*  YOU WON!  *");
            System.out.println("**************");
            System.out.println("Thank you for playing!");

        } else if (g != a) {
            System.out.println("Sorry, better luck next time!");
        }
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
    }


}


推荐答案

我在这里使用了中断继续关键字。

Here I have used break and continue keyword.

while(true) {
    try {
        System.out.print("Enter your guess: ");
        g = input.nextInt();
        if (g == a) {

            System.out.println("**************");
            System.out.println("*  YOU WON!  *");
            System.out.println("**************");
            System.out.println("Thank you for playing!");

        } else if (g != a) {
            System.out.println("Sorry, better luck next time!");
        }
        break;
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
        continue;
    }
}

这篇关于while循环中的try-catch方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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