繁体   English   中英

异常处理

[英]Exceptions handling

我希望它允许用户在输入错误之后输入两个int。 我试着继续; 在catch块中,但是它只会引发运行时错误。 我只希望它在引发错误后返回到main方法的顶部。 看看图片中如何不允许用户输入任何数字。 我要修复该部分。

这是代码。 这仅用于练习。

/**
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"));
     }
   }

摆脱扫描仪缓冲区中的无效输入

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

该代码现在将下拉至System.out.println("Again (y/n)");

如果要循环回到顶部,请在keyboard.next();之后添加一个continue keyboard.next();

暂无
暂无

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

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