Java:如何读取输入int

时间:2013-01-10 13:52:23

标签: java input java.util.scanner

所以,我正在寻找一种有效的方法,使用Java的标准软件包来读取输入整数...例如,我遇到了“扫描仪”这个类,但我发现了两个主要的困难:

  1. 如果我不插入int,我实际上无法解决异常;
  2. 这个类与令牌一起使用,但我的目标是加载字符串的全长。
  3. 这是我想要实现的执行示例:

    Integer: eight
    Input error - Invalid value for an int.
    Reinsert: 8 secondtoken
    Input error - Invalid value for an int.
    Reinsert: 8
    8 + 7 = 15
    

    这是我试图实现的(错误的)代码:

    import java.util.Scanner;
    import java.util.InputMismatchException;
    
    class ReadInt{
        public static void main(String[] args){
            Scanner in = new Scanner(System.in);
            boolean check;
            int i = 0;
            System.out.print("Integer: ");
            do{
                check = true;
                try{
                    i = in.nextInt();
                } catch (InputMismatchException e){
                    System.err.println("Input error - Invalid value for an int.");
                    System.out.print("Reinsert: ");
                    check = false;
                }
            } while (!check);
            System.out.print(i + " + 7 = " + (i+7));
        }
    }
    

2 个答案:

答案 0 :(得分:1)

与令牌一起使用:

int i = Integer.parseInt(in.next());

然后你可以这样做:

int i;
while (true) {
    System.out.print("Enter a number: ");
    try {
        i = Integer.parseInt(in.next());
        break;
    } catch (NumberFormatException e) {
        System.out.println("Not a valid number");
    }
}
//do stuff with i

以上代码适用于令牌。

答案 1 :(得分:1)

使用BufferedReader。检查NumberFormatException。否则非常类似于你所拥有的。像这样......

import java.io.*;

public class ReadInt{
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        boolean check;
        int i = 0;
        System.out.print("Integer: ");
        do{
            check = true;
            try{
                i = Integer.parseInt(in.readLine());
            } catch (NumberFormatException e){
                System.err.println("Input error - Invalid value for an int.");
                System.out.print("Reinsert: ");
                check = false;
            }
        } while (!check);
        System.out.print(i + " + 7 = " + (i+7));
    }
}