At the moment I'm calling the method reader.nextInt()
twice so it's only using the addNumber()
method for every other value rather than each one.
How do I go about fixing this issue?
I've tried using a while loop containing (true) as well as the one printed below, both encounter the same issue.
I forgot to mention, I need the programme to print the sum of all integers entered. This is to be triggered by entering the value of -1. The -1 is meant to be excluded from the sum.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
Scanner reader = new Scanner (System.in);
System.out.println("Type numbers:");
while (reader.nextInt() != -1) {
stats.addNumber(reader.nextInt());
}
System.out.println("sum: " + stats.sum());
}
}
public class NumberStatistics {
private int amountOfNumbers;
private int sum;
public NumberStatistics() {
amountOfNumbers = 0;
sum = 0;
}
public void addNumber(int number) {
this.amountOfNumbers++;
this.sum += number;
}
public int amountOfNumbers() {
return this.amountOfNumbers;
}
public int sum() {
return this.sum;
}
public double average() {
if (this.sum() == 0) {
return 0;
}
else {
return (double) this.sum / this.amountOfNumbers;
}
}
}