《JAVA:异常的处理》NumberFormatException异常

来源:互联网 发布:linux 设置ftp根目录 编辑:程序博客网 时间:2024/05/08 07:44

1.【NumberFormatException异常】编写一个程序,提示用户输入两个整数,然后显示它们的和。用户输入错误时提示用户重新输入。

—-不能把类名声明为你需要捕获的异常类型名,如本题不能写类名为NumberFormatException,也不能在同一个包里面有一个名为NumberFormatException 的类,这是因NumberFormatException 本就是一个代表一种异常的类型,属于Throwable的。这样子一般会出错说NumberFormatException必须属于Throwable类。
—-还有一个问题就是你也不能直接用最基础的Exception类代提NumberFormatException,因为不符合题意,当然其他题目可以,因为简单嘛。

package shiyan6;import java.util.*;public class demo1 {    //千万别把类名写成 NumberFormatException     public static void main(String[] args){        Scanner input = new Scanner(System.in);        boolean inputinteger= true;        System.out.println("Please input two integer:");            do{                 try {                    //输入的数字或字母等都先当成String类型储存                    String number1 = input.nextLine();                    String number2 = input.nextLine();                    int n1 = Integer.parseInt(number1);                    int n2 = Integer.parseInt(number2);                    //不可以可以转化成整数就会产生想要的异常                    //显示结果                    System.out.println("The sum of the two integer is:"+(n1+n2) );                    inputinteger = false;//没错就退出                }                 catch (NumberFormatException e) {                    System.out.println("NumberFormatException!Try to input again:please input the integer!");                }            }while(inputinteger);//输入不对继续输入    }}

输出:
这里写图片描述
这里写图片描述
在编写异常的时候要去百度一下这个异常时什么时候出现的,然后再编写,一般在一个博客园的网站都会有具体的介绍。以上是初学者个人的做法与看法,期待指正。

1 0
原创粉丝点击