Java异常处理

标签 java exception

所以我对捕获错误等有点陌生。不管怎样,程序应该要求用户提供 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.");
}

如果想提示用户重新输入,可以在catch block 中调用getAnswer(),如下所示:

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;
    }

关于Java异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402972/

相关文章:

java - 新的 GWT Maven 插件 (net.ltgt.gwt.maven) : no picking up of gwt. 来自 src/main/resources 的 xml(仅 src/main/java)

java - 在多个 if 语句中调用正则表达式检查方法时使用哪种模式或方法?

java - 使用模拟器和 HttpURLConnection 出现未知主机异常

java - 如何从 web 服务中抛出异常?

postgresql - 在 postgresql 函数中抛出异常

java - 启动Chrome,然后等待其关闭

java - 不区分大小写的字符串过滤器

string - 如何将 Rebol 错误格式化为字符串?

java - 灰熊 Jersey 吞咽异常

javascript - JQuery 无法在 Restful Web 服务中捕获异常。