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!