简体   繁体   English

异常处理

[英]Exceptions handling

I want it allow the user to enter in two int after the incorrect input. 我希望它允许用户在输入错误之后输入两个int。 I tried continue; 我试着继续; in the catch block, but it only threw run-time errors. 在catch块中,但是它只会引发运行时错误。 I just want it to go back to the top of the main method after the throwing the error. 我只希望它在引发错误后返回到main方法的顶部。 See how in the pic it didn't allow the user to input any numbers. 看看图片中如何不允许用户输入任何数字。 I want to fix that part. 我要修复该部分。

Here's the code. 这是代码。 This is only for practice. 这仅用于练习。

/**
practing exceptions, example 1 in book for exceptions 
*/ 

    import java.util.Scanner;

    public class PracticeExceptions extends Exception {

    public static void main(String[] args)
    {
     String response = "y";
     Scanner keyboard = new Scanner(System.in);

     do{ 
     int n1, n2;
     double r;
     System.out.println("Please enter two numbers");

     try{
            n1 = keyboard.nextInt();
            n2 = keyboard.nextInt();
            r = (double) n1/n2;     

        System.out.format("Your answer: %.2f %n", r);

       }catch(Exception a){

       System.out.println("Invaild input please try again");

       }

       System.out.println("Again (y/n)");
       response = keyboard.next();

       }while(response.equalsIgnoreCase("y"));
     }
   }

Get rid of the invalid input in you scanner buffer 摆脱扫描仪缓冲区中的无效输入

 }catch(Exception a){
    System.out.println("Invalid input please try again");
    keyboard.next();
 }

The code will now drop down to System.out.println("Again (y/n)"); 该代码现在将下拉至System.out.println("Again (y/n)");

If you want to loop back to the top add a continue after keyboard.next(); 如果要循环回到顶部,请在keyboard.next();之后添加一个continue keyboard.next();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM