Reputation: 37
Now I looked through many other questions to find similar to mine but for some reason I don't understand how to get the array the user entered to display when calculating the average. If there is a question similar to mine, please send me the link that way I can refer to it. Thank you so much. I want it to show:
"Please enter 5 integers: 25 43 12 5 7"
"You have entered: 25 43 12 5 7 and the average is __"
public class CalcAvg {
public static void main(String[] args) {
double [] userinput = getArrayInfo();
double average = CalculateAvg(userinput);
getAvg(userinput, average);
}
public static double[] getArrayInfo() {
Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userinput =new double[NUM_ELEMENTS];
int i = 0;
System.out.println("Please enter 5 integers: ");
for (i = 0; i < NUM_ELEMENTS; ++i) {
userinput[i] = in.nextDouble();
}
return userinput;
}
public static double CalculateAvg(double[] userinput) {
double sum = 0;
double average = 0;
for (int i = 0; i < userinput.length; i++) {
sum = sum + userinput[i];
}
average = sum / userinput.length;
return average;
}
public static void getAvg(double[] userinput, double average) {
int i = 0;
System.out.println("The average of the numbers " + userinput + " is " +average);
}
}
Upvotes: 1
Views: 66
Reputation: 5331
To produce a String
showing an array in the way you want, probably create a method to do all the String operations for you (and not repeat your code). Create the String
using a StringBuilder
by iterating through the array with a for loop.
public String arrayToString(double[] input) {
StringBuilder builder = new StringBuilder(); // declare this outside of the loop
for (double dub : input) {
builder.append(dub + " ");
}
return builder.toString().trim(); // get rid of trailing spaces
}
Then, to implement this, change the line System.out.println("The average of the numbers " + userinput + " is " +average)
to System.out.println("The average of the numbers " + arrayToString(userinput) + " is " + average)
.
Also, CalculateAvg()
, following naming conventions, would be calculateAvg()
. You can also iterate through the for loop using the 'enhanced for loop' with int x : userinput
instead of the counting variables you are currently using.
Upvotes: 1
Reputation: 1063
All classes inherits from Object and has therefore a toString() method. When you try to print the array, it calls the toString() method that returns the object's class name representation and then "@" followed by its hashcode.
A solution would be:
System.out.println(java.util.Arrays.toString(arr));
Or loop through the elements to print them one by one.
Upvotes: 0