1

对于我正在编写的程序,我需要向用户询问 1 到 8 之间的整数。我尝试了多种(更简洁的)方法,但没有一种方法有效,所以我只剩下这个:

    int x = 0;
    while (x < 1 || x > 8)
    {   
        System.out.print("Please enter integer  (1-8): ");

        try
        {
            x = Integer.parseInt(inputScanner.next());
        }
        catch(NumberFormatException e)
        {
            x = 0;
        }
    }

扫描仪在哪里inputScanner。肯定有更好的方法吗?

4

7 回答 7

4

扫描仪做正则表达式,对吧?为什么不先检查它是否匹配“^[1-8]$”?

于 2009-01-22T22:06:55.493 回答
3

与简单地使用 next() 方法相比,使用 nextInt() 已经是一种改进。在此之前,您可以使用 hasNextInt() 来避免出现所有这些无用的异常。

导致这样的事情:

int x = 0;
do {
  System.out.print("Please...");
  if(scanner.hasNextInt()) x = scanner.nextInt();
  else scanner.next();
} while (x < 1 || x > 8);
于 2009-01-22T22:09:05.737 回答
2

我必须做一个图形界面计算器(仅适用于整数),问题是,如果输入不是整数,测试不允许抛出任何异常。所以我无法使用

try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}

因为 Java 程序通常将 JTextField 的输入视为字符串,所以我使用了这个:

if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
   goodforyou
} else {
   dosomethingelse
}

// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9

希望这可以帮助 :)

于 2012-12-06T17:22:59.347 回答
1

你可以尝试这样的事情:

Scanner cin = new Scanner(System.in);
int s = 0;    
boolean v = false;
while(!v){
    System.out.print("Input an integer >= 1: ");

    try {    
        s = cin.nextInt();
        if(s >= 1) v = true;
        else System.out.println("Please input an integer value >= 1.");
    } 
    catch(InputMismatchException e) {
        System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
        cin.next();
    }
}
于 2015-03-25T05:23:27.643 回答
0
String input;
int number;

while (inputScanner.hasNextLine())
{
    input = inputScanner.nextLine();

    if (input.equals("quit")) { System.exit(0); }
    else
    {
        //If you don't want to put your code in here, make an event handler
        //that gets called from this spot with the input passed in
        try
        {
            number = Integer.parseInt(input);
            if ((number < 1) || (number > 8))
            { System.out.print("Please choose 1-8: "); }
            else { /* Do stuff */ }
        }
        catch (NumberFormatException e) { number = 0; }
    }
}

我总是喜欢拉入完整的字符串,这样您就可以确定用户按下了 Enter 按钮。如果你只是使用inputScanner.nextInt(),你可以把两个ints 放在一条线上,它会拉一个,然后另一个。

于 2009-01-22T22:10:56.420 回答
0

Apache Commons 是您的朋友。请参阅NumberUtils.toInt(String, int)

于 2009-01-22T22:33:04.910 回答
0

示例代码:

int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();

数组也可用于存储整数。

于 2010-09-08T17:55:22.350 回答