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

Recommended Answers

All 2 Replies

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.