使用BufferedReader读取多行整数时出错

时间:2015-07-11 07:26:33

标签: java bufferedreader

我得到了这个例外:

x :: IO String
x = return "hello world"

main = do
  x >>= print

使用此代码时:

Exception in thread "main" java.lang.NumberFormatException: For input string: "55 45 65 88 "
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)

示例输入:

  

4
  55 45 65 88(在这里,当我按下输入时,它给出了上述错误)

2 个答案:

答案 0 :(得分:4)

StringTokenizer不支持正则表达式。

StringTokenizer tokens = new StringTokenizer(line, "\\s+");
// This will look for literal "\s+" string as the token.

请改用

StringTokenizer tokens = new StringTokenizer(line, " "); // Just a space.

编辑:正如@MasterOdin所指出的,StringTokenizer的默认分隔符是空格" "。因此,下面也会以同样的方式工作,

StringTokenizer tokens = new StringTokenizer(line);

答案 1 :(得分:2)

你可以采用简单的方式:

String []m=br.readLine().split(" "); // split the line delimited with space as array of string.
 for(int i=0;i<m.length;i++){
    marks.add(Integer.valueOf(m[i]));  // add to the marks array list
 }

编辑:根据T.G

for (String s : br.readLine().split("\\s+")) {
   marks.add(Integer.valueOf(s));
}