Apaar Bhatnagar
Apaar Bhatnagar

Reputation: 119

Error reading multiple lines of integers using BufferedReader

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)

Upvotes: 1

Views: 254

Answers (2)

Rustam
Rustam

Reputation: 6515

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));
}

Upvotes: 2

Codebender
Codebender

Reputation: 14471

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);

Upvotes: 4

Related Questions