因此,我对于捕捉错误之类是新的。无论如何,该程序应该询问用户2个整数,然后将它们加在一起。很简单,但是如果任何一个数字都不是整数,则会引发错误。当前,如果我输入2个整数而不是将它们相加,它只会重新启动getAnswer()方法并再次输出它们。另外,如果您输入多个错误,它只会退出。

package javaapplication1;

import java.util.InputMismatchException;
import java.util.Scanner;


public class JavaApplication1 {

  public static void main(String[] args) {
    Intro();
    System.out.println("Your answer: "+getAnswer());
  }
  private static void Intro() {
    System.out.println("Hello this program adds 2 integers together and catches errors.");
    getAnswer();
  }
  private static int getAnswer() throws InputMismatchException {
    Scanner scanner = new Scanner(System.in);
    try {
      System.out.println("Please input a number");
      int num1 = scanner.nextInt();
      System.out.println("Please input a second number");
      int num2 = scanner.nextInt();
      return num1+ num2;
    } catch (InputMismatchException exp) {
      System.out.println("Exception thrown");
      return 0;
    }
  }
}

最佳答案

您总共要调用两次getAnswer();,因此只需从Intro()方法中删除该调用即可解决问题。

private static void Intro() {
        System.out.println("Hello this program adds 2
             integers together and catches errors.");
}


如果要提示用户再次重新输入,可以在getAnswer()块中调用catch,如下所示:

private static int getAnswer() {
        Scanner scanner = new Scanner(System.in);
        try {
        System.out.println("Please input a number");
        int num1 = scanner.nextInt();
        System.out.println("Please input a second number");
        int num2 = scanner.nextInt();
       return num1+ num2;
         } catch (InputMismatchException exp) {
           System.out.println("Exception thrown, please reenter values:");
           getAnswer();
        }
       return 0;
 }




还有一点是,除了捕获InputMismatchException之外,另一种更好的方法是将输入读取为字符串,并验证它们仅包含数字值,如下所示:

private static int getAnswer() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please input a number");
        String num1 = scanner.nextLine();
        System.out.println("Please input a second number");
        String num2 = scanner.nextLine();
        if(num1.matches("[0-9]+") && num2.matches("[0-9]+")) {
            return Integer.parseInt(num1)+ Integer.parseInt(num2);
        } else {
            System.out.println(" Your inputs contain Invalid characters");
            getAnswer();
        }
       return 0;
    }

09-04 08:25