I'm doing my homework and it says to write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value.
I was able to get this program working with an overloaded method... but I'm curious to hear your feedback on where I can improve and what I'm not understanding 100%. Please feel free to review this and let me know your constructive feedback as to my code and where you think I can do better.
import java.util.Scanner;
public class PP68 {
public static void main(String [] args) {//start main
Scanner input = new Scanner(System.in); //new object of scanner type
double avg =0, total =0;
double[] average = new double[10]; //double array
for(int i = 0; i < 10; i++){ //enter 10 numbers to average
System.out.print("Enter a number to average.");
average[i] = input.nextDouble();
}
for(int j = 0; j < average.length; j++) {
total = total + average[j];
avg = total / average.length;
}
System.out.println("The average of your arrays numbers is: " + avg);
}//end main
public static int average(int[] array){ //1st method
int total =0;
int avg = total / array.length;
return avg;
}//end 1st method
public static double average(double[] array) {//Second method - overloaded
double total = 0;
double avg = total / array.length;
return avg;
}//end 2nd method
}
New code follows below:
import java.util.Scanner;
public class PP68v2 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 1 to average an INT or hit 2 to average a DOUBLE");
int entry = input.nextInt();
if (entry == 2) { //choose double and call double method
double[] array = new double[10];
for(int i = 0; i < 10; i++){
System.out.println("Enter a number to average.");
array[i] = input.nextDouble();
}
System.out.println("The average of your arrays numbers is: " + average(array));
} else if (entry == 1) { //choose int and call int method
int[] array = new int[10];
for(int b = 0; b < 10; b++) {
System.out.println("Enter a number to average.");
array[b] = input.nextInt();
}
System.out.println("The average of your arrays numbers is: " + average(array));
}
}
public static int average(int[] array){
int total =0;
int avg1 = 0;
for(int b=0; b < 10; b++) {
total = total + array[b];
avg1 = total / 10;
}
return avg1;
}
public static double average(double[] array) {
double total = 0;
double avg = 0;
for(int i =0; i < 10; i++) {
total = total + array[i];
avg = total / array.length;
}
return avg;
}
}