This is my code
import java.util.*;
import java.io.*;
public class eCheck10A
{
public static void main(String[] args)
{
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter your integers");
out.println("Negative = sentinel");
List<Integer> aList = new ArrayList<Integer>();
for (int n1 = in.nextInt(); n1 > 0; n1 = in.nextInt())
{
if(n1 < 0)
{
break;
}
}
}
}
if i want to take all the numbers that I enter for n1, and average them out, how do i refer to all these numbers? I am going to put them in the IF statement, so if a negative number is entered, the program stops and posts their average.
This is the pseudocode you need to do this task (pseudo-code since it looks suspiciously like homework/classwork and you’ll become a better developer if you nut out the implementation yourself).
Because you don’t need the numbers themselves to work out the average, there’s no point in storing them. The average is defined as the sum of all numbers divided by their count, so that’s all you need to remember. Something like this should suffice:
A couple of other points I’ll mention. As it stands now, your
forstatement will exit at the first non-positive number (<= 0), making theifsuperfluous.In addition, you probably want any zeros to be included in the average: the average of
{1,2,3} = 2is not the same as the average of{1,2,3,0,0,0} = 1.You can do this in the
forstatement itself with something like:and then you don’t need the
if/breakbit inside the loop at all, similar to my provided pseudo-code.