简体   繁体   中英

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.

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

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. 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((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((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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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