简体   繁体   English

将从文件读取的数字添加到已初始化为0的totalAmount,从而产生意外结果

[英]Adding numbers read from a file to a totalAmount initialized to 0 giving an unexpected result

I have a small homework application that writes random numbers from 5 to 77 to a text file, and then a separate application that reads the file and totals the numbers. 我有一个小的家庭作业应用程序,将5到77的随机数写入文本文件,然后是一个单独的应用程序,它读取文件并总计数字。

Here is my code for writing the numbers to the text file... 这是我将数字写入文本文件的代码...

Random r = new Random();
    int min = 5;
    int max = 77;
    int[]randomNumbers = new int[1000];

    try
    {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("myTextFile.txt")), true);
        for(int i = 0; i < randomNumbers.length; i++)
        {
            randomNumbers[i] = r.nextInt(max - min + 1) + min;
            pw.println(randomNumbers[i]);
        }

    }
    catch(IOException io){} 

Here is my code for reading the file and totalling the amount... 这是我的阅读文件和总金额的代码......

int totalAmount = 0;

public void run()
{
    try
    {
        BufferedReader buffy = new BufferedReader(new FileReader("myTextFile.txt"));
        String s;

        while((s = buffy.readLine()) != null)
        {
            int number = Integer.parseInt(s);
            totalAmount += number;
            System.out.println(totalNumbers);

        }



    }
    catch(IOException io){}
}

The output however starts with 29633 and displays numbers all the way to 42328 输出然而,随着29633个显示数字开始一路42328

Why do I get this result... just trying to understand the wrong part of my code 为什么我得到这个结果...只是试图理解我的代码的错误部分

You are printing totalNumbers instead of the variable you accumulated your values into ( totalAmount ), which is an uninitialized variable. 您正在打印totalNumbers而不是将您的值累积到的变量( totalAmount ),这是一个未初始化的变量。 Its contents are undefined and unpredictable. 其内容未定义且不可预测。

System.out.println(totalNumbers);
// Should be
System.out.println(totalAmount);

Do you need to print out each number from the file, or only print out the total? 您是否需要打印文件中的每个数字,或者只打印出总数?

If you need to print each number, the while loop in your total application should look like this... 如果您需要打印每个数字, 整个应用程序中的while循环应该如下所示......

    while((s = buffy.readLine()) != null) {
        int number = Integer.parseInt(s);
        totalAmount += number;
        System.out.println(number); // changed the variable here
        }

However, if you only need to print out the final result, you need to move the System.out.println() line outside the while loop (and still change the variable to totalAmount ... 但是,如果您只需要打印出最终结果,则需要在while循环外移动System.out.println()行(并且仍然将变量更改为totalAmount ...

    while((s = buffy.readLine()) != null) {
        int number = Integer.parseInt(s);
        totalAmount += number;
        }
    System.out.println(totalAmount); // changed the variable here, and moved it outside the loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM