如何通过phpMyAdmin和MySQL编辑文章?

时间:2014-03-22 05:11:48

标签: java numberformatexception

我收到以下错误:

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)

我的示例输出是:

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

代码:

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

1 个答案:

答案 0 :(得分:0)

我能够通过输入"来重建您的错误。 23 32"在一条线上:

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

然后Integer.parseInt(keyboard.readLine());尝试从"解析整数23 32"什么给出错误,因为只有数字字符是预期的。也许尝试使用Scanner.nextInt()http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html),这样您就不必关心空格了。

另请注意,average = sum / count会给出错误答案:

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

因为sumcount都是整数,所以将应用整数除法。在这种情况下11/2 = 5。因此,您应该使用average = (double) sum / (double) count

最后一点。在声明时初始化变量是一种很好的做法:

int sum = 0;
int count = 0;