读取整数输入时出错

时间:2014-09-19 17:46:39

标签: java

输入:

2

我的节目:

 public static void main(String args[] ) throws Exception {
        /*
         * Read input from stdin and provide input before running*/

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


        String line = br.readLine();

        int cases = Integer.parseInt(line);}

错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "2 "
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)

如何解决这个问题我希望案例的值= 2;怎么了?

1 个答案:

答案 0 :(得分:3)

你需要trim你的字符串

int cases = Integer.parseInt(line.trim());}