如何使用Try / Catch来防止在需要Int的地方输入String

时间:2016-10-19 06:02:47

标签: java try-catch

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package freetime;

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

/**
*
* @author Andy
*/
public class NewClass {
public static void main(String[] args){
    Scanner scan=new Scanner(System.in);
    int userInput=0,notInt=0,newInput=0;
    System.out.println("Enter a integer number");
    while (notInt == 0){
        try {
            newInput=scan.nextInt();
            userInput=newInput;
            if (userInput != newInput){
                notInt=0;
            }
            if (userInput == newInput){
                notInt=1;
            }
        }
        catch(InputMismatchException e){
            System.out.println("That is not an integer, please try again." );
        }
    }
    System.out.println(userInput);

 }
}

我正在尝试阻止字符串输入并允许用户重新输入为int。我似乎无法让它正常工作,我也没有while循环这样做。我认为我对Try Mismatch函数如何工作的理解导致了一些问题。

感谢您的帮助。

Scanner scan=new Scanner(System.in);
    int userInput=0,notInt=0,newInput=0;
    boolean runL=true;
    while (runL){
        System.out.println("Enter a integer number");
        if (scan.hasNextInt()){
           userInput=scan.nextInt();
           runL=false;
        }
        else {
            System.out.println("That is not an integer, please try again.");
        }
    }
    System.out.println(userInput);

所以我把代码更改为了这个但是我仍然在循环中继续追求输入int以外的东西。我做错了什么?

    int userInput=0,notInt=0,newInput=0;
    boolean runL=true;
    while (runL){
        Scanner scan=new Scanner(System.in);
        System.out.println("Enter a integer number");
        if (scan.hasNextInt()){
           userInput=scan.nextInt();
           runL=false;
        }
        else {
            System.out.println("That is not an integer, please try again.");
        }
    }
    System.out.println(userInput);

我发现了问题,我需要在While循环内创建扫描仪对象。谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

在try块中使用Integer.parseInt(input)。 如果input不是int,那么它将抛出异常并捕获catch{} block中的异常。

答案 1 :(得分:0)

你的while循环应如下所示:

while (notInt == 0){
    try {
        newInput=Integer.parseInt(scan.nextLine());
        userInput=newInput;
        notInt=1;
    }
    catch(NumberFormatException e){
        System.out.println("That is not an integer, please try again." );
    }
}

您的代码无效,因为抛出InputMismatchException时,实际上并未读取导致异常的令牌。所以循环在每次迭代时读取相同的东西。

然而,

nextLine几乎总是将整行读作字符串(除非没有行)。您将读取的字符串放入Integer.parseInt以将其转换为int。如果无法将其转换为int,则会抛出NumberFormatException

但是,您不应该使用异常作为验证输入的方法,因为它很慢。您可以使用正则表达式尝试此方法:

while (notInt == 0){
    String line = scan.nextLine();
    Pattern p = Pattern.compile("-?\\d+");
    if (p.matcher(line).matches()) {
        userInput = Integer.parseInt(line);
        notInt = 1;
    } else {
        System.out.println("Please try again");
    }
}

答案 2 :(得分:0)

  

我认为我对Try Mismatch功能如何工作的理解导致了一些问题。

你可能就在那儿......

当我删除一些"奇怪的"您的try / catch语句中的代码如下所示:

    try {
        newInput = scan.nextInt();
        // do stuff
    } catch (InputMismatchException e){
        // do other stuff
    }

这是实际意味着什么:

  1. 致电scan.nextInt()

  2. 如果通话成功(即它没有抛出异常),则:

    1. 将结果分配给newInput

    2. "做东西"

  3. 如果通话失败,并且它投了InputMismatchException,那么:

    1. "做其他事情"
  4. 所以,基于此,你不需要在"做东西"测试你是否得到了有效的输入。您知道就是这种情况。

    同样地,在没有得到有效输入的情况下需要做的任何事情应该在"做其他事情"。

    话虽如此,Jon Skeet关于hashNextInt方法的建议仍然存在。如果你以正确的方式使用它,你根本就不会得到例外。代码会简单得多。

    Jon也是正确的,你应该使用boolean类型来表示你的真/假逻辑。 (这就是该类型的用途!)