1

I am getting this exception:

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)

while using this code:

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

String line = br.readLine();
int noOfStudents = Integer.parseInt(line); //firstline contains 1 integer.

ArrayList <Integer> marks = new ArrayList<Integer>();

line = br.readLine(); //second line contains a line of integers

StringTokenizer tokens = new StringTokenizer(line, "\\s+");
// to break the line into tokens 

while (tokens.hasMoreTokens())
{
    marks.add(Integer.valueOf(tokens.nextToken())); //error here
    //when I am converting tokens into integers its giving error
}

Sample input:

4
55 45 65 88 (here, when I press enter it gives me the above stated errors)

Tom
  • 14,120
  • 16
  • 41
  • 47

2 Answers2

4

StringTokenizer doesn't support regex.

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

Use this instead,

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

Edit: As @MasterOdin has pointed out, StringTokenizer's default delimiter is a space " ". Hence the below would also work the same way,

StringTokenizer tokens = new StringTokenizer(line);
Codebender
  • 13,431
  • 6
  • 40
  • 83
2

you can go for simple way as:

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
 }

EDIT : AS per T.G

for (String s : br.readLine().split("\\s+")) {
   marks.add(Integer.valueOf(s));
}
T.G
  • 1,773
  • 1
  • 15
  • 28
Rustam
  • 6,307
  • 1
  • 21
  • 25
  • It's good to have alternative, but in this case i would not recommend this solution. It is better to learn to use classes instead of writing your own code, Ofc. it is good to be able to write those classes on your own ;) – T.G Jul 11 '15 at 07:51
  • @Rustam: since `split` supports regex, you can keep the `\\s+` there. – Tom Jul 11 '15 at 07:57
  • Hmm didn't noticed that. You very much right. `split()` is much efficient. But why use `fori` loop if you can use `foro`? – T.G Jul 11 '15 at 07:58
  • @T.G Some still use `StringTokenizer` [since it can have a better performance](http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split), but these are rare cases. And yes, an enhanced `for` loop is better here. – Tom Jul 11 '15 at 08:01
  • Thanks for the improvement @T.G – Rustam Jul 11 '15 at 08:02