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


如果我不插入整数,则实际上无法解决该异常;
该类可用于标记,但我的目的是加载字符串的完整长度。


这是我想了解的执行示例:

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));
    }
}

最佳答案

使用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));
    }
}

08-17 19:05