如何在 java 中使用 BufferedReader 获取整数(2 位或更多位)输入

How to take integer(2 or more digit) inputs using BufferedReader in java

这是我的代码:

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
        String s = b.readLine();
        for (int i = 0; i < s.length(); i++)
        {
            if (i % 2 == 0) {
                int a = Integer.parseInt(String.valueOf(s.charAt(i)));
                System.out.print(a);
            }
        }
    }
}

这段代码对于个位数的整数效果很好,但如果输入是两位数,那就乱七八糟了。

我的输入:1 3 6 5 7 输出:1 3 6 5 7 效果很好 但, 如果输入是:1 3 66 58 7 输出:发生异常。 如何处理这样的两位数整数输入。

只需尝试解析使用 readLine() 获得的整行:

String s = b.readLine();
int a = Integer.parseInt(s);

如果该字符串不是数字,您将得到异常。

"my input: 1 3 6 5 7 output: 1 3 6 5 7 works well but, 
if the input is : 1 3 66 58 7 output: exception occurs. 
how to handle such double digit integer inputs."

基于此,确实不清楚您要完成什么。您得到的异常是因为您的 if (i % 2)。当您输入 1 3 66 58 7 时,您的代码会处理 1,跳过 space,处理 3,跳过 space,处理 6而不是 66,跳过第二个 6,然后处理 space,这就是发生异常的时候。

您的示例代码表明您只是试图将由 space 分隔的每个数字字符串转换为整数。

一种方法是使用 String.split() 将输入拆分为 space 并尝试转换每一部分。

类似于:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Whosebug {
    public static void main(String[] args) throws Exception {
        BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
        String s = b.readLine();
        String[] pieces = s.split(" ");

        for (int i = 0; i < pieces.length; i++) {
            try {
                int a = Integer.parseInt(pieces[i]);
                System.out.print(a + " ");
            } catch (Exception e) {
                System.out.printf("%s is not an integer\r\n", pieces[i]);
            }
        }
    }
}

结果:

1 3 66 58 7 // Input
1 3 66 58 7 // Output