如何在字符串的情况下处理异常

时间:2015-05-18 11:12:02

标签: java string exception exception-handling

我在整数变量中输入字符串值时出错。我想知道处理异常,因为我的程序给出的指示是再次输入您的值,而不是停止并给出异常处理错误。

System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
int a=obj1.nextInt();     //I am entering string value here
System.out.println(a);
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at javaapplication13.JavaApplication13.main(JavaApplication13.java:23)

4 个答案:

答案 0 :(得分:4)

最好防止抛出异常而不是处理异常,因为创建异常对象可能非常昂贵。如果是Scanner类,您的代码可能如下所示:

Scanner scanner = new Scanner(System.in);

System.out.println("Please enter a number:");

while(!scanner.hasNextInt()){//while user is not providing valid int
    //inform him about it
    System.out.println("that was not valid integer, please try again: ");
    //and consume invalid value (maybe even entire line)
    scanner.nextLine();
}
//since we are out of loop it must mean that user entered valid int, lets store it
int a = scanner.nextInt();

System.out.println(a);

您还可以将此代码包装在一些不错的实用程序方法中,您甚至可以在其中添加对最大尝试次数的支持。对于那种代码,您可以将其用作结果Optional<Integer>。如果用户

,这将允许我们清除信息
  • 提供了正确的值,我们将使用此值返回Optional
  • 或者如果他没有这样做,在这种情况下我们可以返回空的Optional。

这是处理可能不存在的结果的最简洁方法

如果没有Optional,我们要么:

  • 返回一些默认值,如:
    • -1但在这种情况下,我们不知道-1是否代表无效输入,或者用户是否实际提供了-1,这意味着它可能是正确的结果
    • null(如果我们将返回类型更改为Integer),但这样我们就会让我们的程序员使用我们的方法来检查if(result != null)这对许多人来说可能不那么明显程序员(使用Optional让我们清楚地知道结果可能不存在,所以程序员知道他应该检查这种可能性。)
  • 抛出异常,但由于我们创建方法的原因是为了避免创建和处理异常,这将是一种愚蠢的行为。

所以你的方法看起来像

//-1 represents infinite number of tries
public static Optional<Integer> readInt(Scanner sc, String msg, int tries){
    System.out.println(msg);

    int counter = 0;
    //while user still has more tries but is providing invalid int 
    while((tries == -1 || counter < tries) && !sc.hasNextInt()){
        //inform him about wrong data
        if (tries == -1 || ++counter < tries)
            System.out.println("That was not valid integer. Please try again:");
        else
            System.out.println("That was not valid integer.");
        //and consume invalid value (maybe even entire line)
        sc.nextLine();
    }
    // since we are out of loop it must mean that user entered valid int 
    // or run out of tries
    if (tries == -1 || counter < tries)
        return Optional.of(sc.nextInt());
    else
        return Optional.empty();
}

它的用法看起来像

Scanner scanner = new Scanner(System.in);

Optional<Integer> result = readInt(scanner, "Please enter a number:", 1);

if(result.isPresent()){
    System.out.println(result.get());
}else{
    System.out.println("User failed to give valid integer. Program will terminate");
}

答案 1 :(得分:0)

使用此

        System.out.println("Please enter a number");
    Scanner obj1=new Scanner(System.in);
    if(obj1.hasNextInt())
    {
    int a=obj1.nextInt();     //I am entering string value here
    System.out.println(a);
    }

答案 2 :(得分:0)

将代码放在try-catch块中以处理InputMismatchException

System.out.println("Please enter a number");
Scanner obj1=new Scanner(System.in);
try {
  int a=obj1.nextInt();  
}
catch(InputMismatchException ime) {
  /*show error message for incorrect input*/
}
catch(Exception e) {
 /*Show error message*/
}
System.out.println(a);

希望,这解决了这个问题。

答案 3 :(得分:0)

你可以试试这个......

Win32API.GetKeyState(Asc("A"))