- #1
smilesofmiles
- 19
- 0
I want to alter my program so it can take an unknown amount of elements (user inputs). I want the program to automatically count the numbers the user is inputting up until they hit enter to the next line. I think I got the program to keep track of this but now my output is a bunch of zeros in place of the user numbers. I don't know how to fill the array with the user numbers as well as keep track of the array size. I have attached a screenshot of the output.
Please let me know if I've been unclear. Any help, direction or hints will be greatly appreciated. I feel like I'm really close to solving this.
Thank you! :-)
View attachment 5682
Please let me know if I've been unclear. Any help, direction or hints will be greatly appreciated. I feel like I'm really close to solving this.
Thank you! :-)
View attachment 5682
Code:
package calcavg;
import java.util.Arrays;
import java.util.Scanner;public class CalcAvg { public static double [] getArrayNumbers(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers all one line separated by spaces.");
String lines = input.nextLine();
String[] strs = lines.split(" ");
double userNumbers[] = new double[strs.length];
/* I originally tried this to get the numbers from the user but this asks the user for a number amount to
set the size of the array which I don't want.
System.out.println("Please enter amount of numbers to average.");
int numbers = input.nextInt( );
double [ ] userNumbers = new double[numbers];
System.out.println("Please enter five to ten numbers separated by spaces on one line.");
for (int i = 0; i < userNumbers.length; i++) {
userNumbers[i] = input.nextInt( );
}
*/
return userNumbers;
}
public static double calculateAverage(double [ ] userNumbers){
int counter;
double userSum = 0;
for(counter = 0; counter < userNumbers.length; counter++){
userSum = userSum + userNumbers[counter];
}
return (userSum / counter);
}
public static void printResults(double [] userNumbers, double average){
System.out.print("The average of the numbers " + Arrays.toString(userNumbers) + " is ");
System.out.printf("%.2f", average);
System.out.print(".");
}
public static void main(String[] args){
double userNumbers[] = getArrayNumbers();
double average = calculateAverage(userNumbers);
printResults(userNumbers, average);
}
}