Question

I'm getting the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: " 23 32"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.parseInt(Integer.java:615)
    at javaapplication4.JavaApplication4.main(JavaApplication4.java:28)

My example output is:

Enter positive integers, one number per line, ending with -1 
56    46    47    31    11
The sum of the numbers is 191
The average is 38.2

Code:

package javaapplication4;

import java.io.*;

public class JavaApplication4 {
    public static void main(String[] args) throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader keyboard = new BufferedReader(in);

        int num;
        int sum;
        int count;
        double average;

        System.out.println("Enter positive integers, one number per" +
        "line, ending with ..1");
        count = 0;
        sum = 0;
        num = Integer.parseInt(keyboard.readLine());

        while(num != -1){ sum = sum + num;
            count++;
            num = Integer.parseInt(keyboard.readLine());
        }
        System.out.println("The sum of the number is: " + sum);
        if(count !=0)
        average = sum / count;
        else
            average = 0;
        System.out.println("The average is: "+ average);
    }
}
Was it helpful?

Solution

I was able to reconstruct your error by entering " 23 32" on a single line:

Enter positive integers, one number perline, ending with ..1
 23 32
Exception in thread "main" java.lang.NumberFormatException: For input string: " 23 32"

Then Integer.parseInt(keyboard.readLine()); tries to parse an Integer from " 23 32" what gives error as only digit characters are expected. Maybe try to using Scanner.nextInt() (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) so that you don't need to care about whitespaces.

Also note that average = sum / count will give you wrong answer:

Enter positive integers, one number perline, ending with ..1
5
6
-1
The sum of the number is: 11
The average is: 5.0

as sum and count are both integers so integer division will be applied. In this case 11/2 = 5. Therefore you should use average = (double) sum / (double) count.

And a final note. It's a good practice to initialize variables at declaration time:

int sum = 0;
int count = 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top