Exception handling 试着把两个数相加
我正在处理异常并制作一个新的Java项目。程序等待用户从键盘输入2个数字。如果用户键入两个整数,它将对这些数字求和。如果用户不键入数字,程序将打印“键入数字!”在屏幕上。以下是我尝试过的:Exception handling 试着把两个数相加,exception-handling,try-catch,Exception Handling,Try Catch,我正在处理异常并制作一个新的Java项目。程序等待用户从键盘输入2个数字。如果用户键入两个整数,它将对这些数字求和。如果用户不键入数字,程序将打印“键入数字!”在屏幕上。以下是我尝试过的: public static void main(String[] args) { int a = 0; int b = 0; System.out.println("Type two numbers"); Scanner scan = new Scanner(System.in
public static void main(String[] args) {
int a = 0;
int b = 0;
System.out.println("Type two numbers");
Scanner scan = new Scanner(System.in);
try {
a = scan.nextInt();
b = scan.nextInt();
} catch (Exception ex) {
System.err.println("Type number!");
}
}
请尝试下面的代码。它应该像您期望的那样工作:
public static void main(String[] args) {
System.out.println("Type two numbers");
sum();
}
private static void sum(){
int a = 0;
int b = 0;
Scanner scan = new Scanner(System.in);
try {
a = scan.nextInt();
b = scan.nextInt();
System.out.println(a+b);
} catch (Exception ex) {
System.err.println("Type numbers in correct format!");
sum();
}
}
那么问题到底是什么呢?确切的问题是,如果用户没有键入整数值,当我们要对这些数字求和时会出现错误。所以我没有编写求和操作OK,但您的问题是什么?你是在问如何打印两个数字的总和吗?非常感谢。你为什么要写private?如果静态void sumYes前面没有关键字,它就会工作。private是可选的。这和实际问题没有多大区别