java - average

Reply Sat 3 Apr, 2010 12:55 am
This program has a class that accept from 0 to 5 command-line arguments representing numbers, and should calculate the average.

This is what I got so far but it doesn't work. Could someone help me out please.

package cis;
import java.util.Scanner;

public class MathUtil {

public static void main(String[] args) {
final int NUMBER_OF_ELEMENTS = 5;
double[] numbers = new double[NUMBER_OF_ELEMENTS];
double sum = 0;

java.util.Scanner input = new java.util.Scanner(System.in);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print("Enter a new number: ");
numbers = input.nextDouble();
sum += numbers;
double average = sum / NUMBER_OF_ELEMENTS;

System.out.println("Average is: " + average);



BTW I use eclipse.
  • Topic Stats
  • Top Replies
  • Link to this Topic
Type: Question • Score: 0 • Views: 1,409 • Replies: 2
No top replies

Nick Ashley
Reply Mon 5 Apr, 2010 11:00 am
When you say "It doesn't work" what do you mean by that? Is it thowing an error when you try to compile? At runtime? If so, what error is it throwing?

Or does the program execute ok, but give unintended results? If so, what is the result you are expecting, and what is the result it returns instead?
0 Replies
ebrown p
Reply Mon 5 Apr, 2010 11:20 am
You have a type mismatch. You are defining "numbers" as an array of doubles. Then you are setting it to input.nextDouble() (which returns a double).

You want to do one of two things.

1) Define "numbers" as a double (not an array of doubles). In this case you probably want to change its name to something like "number".

2) Use "numbers" as an array. In this case in stead of saying "numbers = input.nextDouble();" you would say "number[ i ] = input.nextDouble();"

It seems to me you really want the first option (as this is the simplest way to make this program work).

0 Replies

Related Topics

Disable Java? - Discussion by engineer
java jws - Question by rockerpham
Ubuntu, Java and Aptana Studio 3 - Question by Ken Dawson
Java Question,time converter. - Question by Loh Jane
unescape javascripts - Question by happy5
Java Programming Question? - Question by evang14
What is introspection ? - Question by Kathleenortan
  1. Forums
  2. » java - average
Copyright © 2018 MadLab, LLC :: Terms of Service :: Privacy Policy :: Page generated in 0.03 seconds on 01/19/2018 at 07:00:52