【问题标题】:Determining if number entered is an int [duplicate]确定输入的数字是否为 int [重复]
【发布时间】:2014-08-03 11:21:05
【问题描述】:
import java.util.Scanner;

public class test {

/**
 * @param args
 */
public static void main(String[] args) 
{
    Scanner input = new Scanner (System.in);
    boolean US1 = false;
    boolean game;
    int score = 1;
    int wage = 0;   
    int fin_score = 0;
    String ans;

    if (US1 == false) {
        game = false;
        System.out.println (score);
        System.out.println("Enter a wager");
        wage =  input.nextInt();
    }

    if (wage < score) {
        System.out.println ("What is the capital of Liberia?");
        ans = input.next();

        if (ans.equalsIgnoreCase("Monrovia")) {
            System.out.println ("You got it right!");
            System.out.println ("Final score " + fin_score);
        }
    }
}
}

我找到了一堆使用 InputMismatchException 和 try{}catch{} 的解决方案,但是当它们在我的代码中实现时它们永远不会起作用。有没有办法在这里实现这些?我正在尝试创建一个循环,直到输入的工资为整数为止

【问题讨论】:

  • 当然,这种方法(使用 try/catch)是有效的。因此(未显示的)实现一定有问题。
  • 你试过什么?我保证在这种情况下使用在线解决方案会起作用。

标签: java


【解决方案1】:

您可以在代码中使用多个 catch 异常来检查错误输入。例如

try{

    wage = input.nextInt();

catch (InputMismatchException e){ 
   System.out.print(e.getMessage());
   //handle mismatch input exception
}

catch (NumberFormatException e) {
    System.out.print(e.getMessage());
    //handle NFE 
}

catch (Exception e) {
    System.out.print(e.getMessage());
    //last ditch case
}

其中任何一个都可以很好地解决扫描仪错误,但InputMismatchException 是最好用的。如果您在 try-catch 块中包含非工作代码,将对您的案例有很大帮助。

【讨论】:

  • 不回答问题...“我正在尝试创建一个循环,直到输入的工资为整数”。此外,nextInt 对标准输入不利,它不会查看整行来判断它是否有效,并且会在行上留下任何其他单词/整数。
【解决方案2】:

首先,您应该使用Scanner.nextLine,因为Scanner.nextInt 使用空格和换行符作为分隔符,这可能不是您想要的(空格后的任何内容都会留在扫描仪上,破坏任何下一次读取)。

试试这个:

boolean valid = false;
System.out.print("Enter a wager: "); //Looks nicer when the input is put right next to the label
while(!valid)
    try {
        wage = Integer.valueOf(input.nextLine());
        valid = true;
    } catch (NumberFormatException e) {
        System.out.print("That's not a valid number! Enter a wager: ");
    }
}

【讨论】:

  • 我将把它放在我的代码中的什么位置?它可以工作,但是当我输入一个整数时它会崩溃
  • @user3734973:用我给你的替换System.out.println("Enter a wager ");wage = input.nextInt();。另外,如果您的程序使 java crash,那么我建议您重新安装它。如果它只是给你一个例外,那么粘贴你的例外!
【解决方案3】:

是的!有一个好方法可以做到这一点:

Scanner input = new Scanner(System.in);
    boolean gotAnInt = false;
    while(!gotAnInt){
        System.out.println("Enter int: ");
        if(input.hasNextInt()){
            int theInt = input.nextInt();
            gotAnInt = true;
        }else{
            input.next();
        }

    }

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 2018-05-08
    • 2018-05-11
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    相关资源
    最近更新 更多