0
import java.util.Scanner;
class CalcAvg{
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		int sum = 0;
		int avg = 0;

		for(int i = 0; i < 10; i++){
		System.out.println("Enter a number: ");
		int num = s.nextInt();
		sum = sum+num;
		}
		avg = sum/10;
		System.out.println("The sum is: " + sum);
		System.out.println("The average is: " + avg);
	}
}

So I've written this code, its correct, though I would like to have the user input an unknown amount of numbers instead of 10 then stopping it by hitting a character or enter. How do I do that?

Thanks

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by kvass
0
import java.util.Scanner;
class CalcAvg{
	public static void main (String args[]){
		Scanner s = new Scanner(System.in);
		int sum = 0;
		int avg = 0;
                int count=0;
                System.out.println("Enter a number: ");
                int num=s.nextInt();
                 if(num==0||num==1||num==2||nu..............
                   ..............||num==9)
		{
                    count++;
                    sum = sum+num;
		System.out.println("Enter a number: ");
		int num = s.nextInt();
		
		}
		avg = sum/count;
		System.out.println("The sum is: " + sum);
		System.out.println("The average is: " + avg);
	}
}

try the pervious code, and I hope tha's will be useful to you.

0

I have no idea how what e-man suggested will work at all...

Here's what I would do:

print "Enter series of numbers to calculate the average.  Enter 0 to end."
while exit is false:
    Prompt user for #.
    if # is 0, set exit to true.
    otherwise, add that number to "sum" and add 1 to "num".
ave = sum / num
print ave

That would be my basic algorithm. Try to implement it in Java. I suggest using a do-while loop.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.