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

这是我的代码:


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 输出:发生异常。如何处理这样的两位整数输入。


缥缈止盈
浏览 229回答 2
2回答

白猪掌柜的

试着解析你用 readLine() 得到的整行:String s = b.readLine();int a = Integer.parseInt(s);如果该字符串不是数字,您将收到异常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java