我正在研究异常处理并制作一个新的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);
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();
}
}
public class Errors {
public static void main(String[] args) {
System.out.println("Enter an Integer Value for addition:-");
Scanner sc = new Scanner(System.in);
int user = 0;
int user2 = 0;
try {
System.out.println("Enter value A");
user = sc.nextInt();
try {
System.out.println("Enter value B");
user2 = sc.nextInt();
System.out.println(user+user2);
}catch (Exception e){
System.err.println("Please enter an Integer Value");
}
}catch(Exception e){
System.err.println("Please enter an Integer value ");
}
}
}