# Calculate the average

Printable View

• November 2nd, 2013, 11:09 AM
Anais
Calculate the average
I wrote a code to calculate the average of numbers. The problem is that you only can insert whole numbers. Does anybody know how I can change the code so that I can insert float numbers?

Here's the code i did with the help of a tutorial:

Dies ist der Code:

public class main_class {
public static void main(String[] args){
String sentinel = "";
int sum = 0;
int counter = 0;
double mean = 0.0;
Scanner NumScanner = new Scanner(System.in);

System.out.println("Enter numbers to add. Enter \"d\" when done.");

System.out.print("Enter number: ");
sentinel = NumScanner.next();
System.out.println();

while(!sentinel.equals("d") && !sentinel.equals("D")) {
sum += Integer.parseInt(sentinel);
counter++;

System.out.print("Enter number: ");
sentinel = NumScanner.next();
System.out.println();
}

mean = (sum*1.0)/counter;

System.out.println();
System.out.println("The arithmetic mean is: " + mean +".");
}
}
• November 2nd, 2013, 01:35 PM
Norm
Re: Calculate the average
The Scanner class has methods for reading different types of numbers.
Also the Double class has a method for converting a String to a double.
Take a look at the API doc: Java Platform SE 7

Please edit your post and wrap your code with code tags:
[code=java]
YOUR CODE HERE
[/code]
to get highlighting and preserve formatting.
• November 2nd, 2013, 02:13 PM
JavaDIV
Re: Calculate the average
Original code below. Dont know the answer as im not too good at coding.

Code :

```public class main_class { public static void main(String[] args){ String sentinel = ""; int sum = 0; int counter = 0; double mean = 0.0; Scanner NumScanner = new Scanner(System.in);   System.out.println("Enter numbers to add. Enter \"d\" when done.");   System.out.print("Enter number: "); sentinel = NumScanner.next(); System.out.println();   while(!sentinel.equals("d") && !sentinel.equals("D")) { sum += Integer.parseInt(sentinel); counter++;   System.out.print("Enter number: "); sentinel = NumScanner.next(); System.out.println(); }   mean = (sum*1.0)/counter;   System.out.println(); System.out.println("The arithmetic mean is: " + mean +"."); } }```
• November 2nd, 2013, 02:31 PM
Norm
Re: Calculate the average
I suggested two different ways to get float numbers:
1) use a Scanner class method to read the data as float from the user
2) use a Double or Float class method to convert the String read from the user to a double/float

BTW The posted code has lost all its formatting. The statements should not all start in the first column. Nested statements should be indented.
• November 9th, 2013, 01:49 AM
D.K
Re: Calculate the average
Change the integers & doubles to floats and let the scanner read it as a float [scan.nextFloat();].
Note: make sure you import the scanner class (java.util.Scanner;).
• November 16th, 2013, 06:57 AM
Anais
Re: Calculate the average
Thank You! :)