0

so I am working through MOOCfi and I am on the statistics problem. It's straightforward, just input numbers and return the sum of it until user enters -1. Here are the two classes:

Main.java

import java.util.Scanner;

public class Main {
    public static void  main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Statistics statistics = new Statistics();

        while(true) {

            int input = Integer.parseInt(scanner.nextLine());

            if (input == -1) {
                System.out.println("Count: " + statistics.getCount());
                System.out.println("Sum: " + statistics.sum());
                System.out.println("Average: " + statistics.average());
                break;
            }

            statistics.addNumber(input);

        }
    }
}

Statistics.java

public class Statistics {
    private int count;
    private int sum;

    public Statistics() {
        this.count = 0;
    }

    public void addNumber(int number) {
        this.count += 1;
        this.sum += number;
    }

    public int getCount() {
        return this.count;
    }

    public int sum() {
        return this.sum;
    }

    public double average() {
        return (1.0)*(this.sum/this.count);
    }
}

My question is, for the line int input = Integer.parseInt(scanner.nextLine()). I wrote earlier:

if (Integer.parseInt(scanner.nextLine())

AND then

statistics.addNumber(Integer.parseInt(scanner.nextLine())

a few lines down, it whenever I ran it, it gave me some buggy inputs. Sometimes I would have to input -1 twice in order for it to stop, and by that point, the results were wrong. Specifically, entering 5,2,2 gave me a

Count: 2
Sum: 1
Average: 0.0

when it should be

Count: 3
Sum: 9
Average: 3.0

It seems like the if statement ALSO needs the int input rather than the Integer.parseInt(scanner.nextLine()) because putting that in there while keeping statistics.addNumber(input) yields a completely different answer if they were flipped. Is this some sort of weird java thing where assigning Integer.parseInt(scanner.nextLine()) to a int is different than just using it straight up?

Thank you!

  • 4
    ***Every*** call to `nextLine()` retrieves the next line of input, so if you do `if (nextLine()) { print(nextLine()) }` you skip the first line and print the second line. – Andreas Jun 30 '20 at 04:43
  • @ScaryWombat Although the code has the problem identified in the duplicate ([Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/q/4685450/5221149)), that is actually not the *main* problem being asked about here, since `9/3` would not cause that issue to present itself. – Andreas Jun 30 '20 at 04:45
  • Entering `5 2 2 -1` and only picking the alternate numbers (`2` and `-1`) because of the double call to `nextLine()` *will* result in `Count: 2` `Sum: 1` – Andreas Jun 30 '20 at 04:48
  • @Andreas Ok reopened – Scary Wombat Jun 30 '20 at 04:51

0 Answers0