1

int num只需要接受数字。如果我输入字母,我会收到错误消息。有没有办法立即标记字母,还是我必须将num其作为字符串并运行循环?

import java.util.Scanner;

public class Test 
{        
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Input a number.");
        int num = input.nextInt();
    }
}
4

2 回答 2

1

您必须使用Scanner.hasNextInt():

如果此扫描仪输入中的下一个标记可以使用该nextInt()方法解释为默认基数中的 int 值,则返回 true。扫描仪不会超过任何输入。

public static void main(String[] args) 
 {
 System.out.println("Input a number.");
 Scanner sc = new Scanner(System.in);
 System.out.print("Enter number 1: ");
 while (!sc.hasNextInt()) sc.next();
 int num = sc.nextInt();

 System.out.println(num);

 }
于 2012-09-23T05:59:57.947 回答
0

你可能想做这样的事情:

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

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input an integer.");
        int num = 0;  // or any other default value
        try {
            num = input.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("You should've entered an integer like I told you. Fool.");
        } finally {
            input.close();
        }
    }
}

如果用户输入的不是整数,catch块内的代码将被执行。

于 2012-09-23T05:53:32.413 回答