簡體   English   中英

為什么我的求和程序會拋出 NumberFormatException?

[英]Why does my summation program throw a NumberFormatException?

我想從文件中讀取數字並總結總數,但我似乎無法正確處理數據。 它成功地輸出了數字,但沒有成功地將它們相加。

我的代碼:

import java.io.*;
import java.util.*;

public class Q1 {
    public static void main(String[] args) throws IOException {
        StringBuffer str = new StringBuffer();      
        FileWriter output = new FileWriter("number.txt");
        Random r = new Random();

        for (int i = 1; i < 101; i++) {
            str.append(r.nextInt(100) + " ");
        }
        output.write(str.toString());
        System.out.println(str.toString());
        output.close();
        FileReader reader = new FileReader("number.txt");
        BufferedReader input = new BufferedReader(reader);
        String line = input.readLine();
        int total = 0;

        while (line != null) {
            System.out.print(line);
            total += Integer.parseInt(input.readLine());
        }
        System.out.println(total);
    }
}

和堆棧跟蹤:

Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Q1.main(Q1.java:42)

您不會在輸出中附加結束行字符。 試試這個片段:

    StringBuffer str = new StringBuffer();

    FileWriter output = new FileWriter("number.txt");

    Random r = new Random();
    for (int i = 1; i < 101; i++) {

        str.append(r.nextInt(100)).append('\n');

    }
    output.write(str.toString());
    System.out.println(str.toString());
    output.close();

    FileReader reader = new FileReader("number.txt");
    BufferedReader input = new BufferedReader(reader);

    String line;
    int total = 0;

    while ((line = input.readLine())!=null) {

        total += Integer.parseInt(line);
    }
    System.out.println(total);

如果輸出看起來很奇怪,請檢查輸出的創建位置。 這通常是您會發現問題的地方。 還添加了一些小的更改,讓您了解一種不同的方法,可以讓您的生活更輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM