0
   

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: 2,113 • Replies: 2
No top replies

 
Nick Ashley
 
  2  
Reply Mon 5 Apr, 2010 11:00 am
@rockerpham,
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
 
  2  
Reply Mon 5 Apr, 2010 11:20 am
@rockerpham,
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
java to mips - Question by themanwhoknowsandask
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
 
  1. Forums
  2. » java - average
Copyright © 2024 MadLab, LLC :: Terms of Service :: Privacy Policy :: Page generated in 0.05 seconds on 12/21/2024 at 07:16:11