I need to create a program that will calculate an average of arrays up to 10 numbers. Here are the requirements:
The program uses methods to:
1.Get the numbers entered by the user
2.Calculate the average of the numbers entered by the user
3.Print the results
The first method should take no arguments and return an array of doubles that the user entered.
The second method should take an array of doubles (the return value of the first method above) as its only argument and return a double (the average).
The third method should take an array of doubles and a (single) double value as arguments but have no return value.
I tried the below, but the biggest problem I'm running into (that I can tell so far at least) is that the program is printing both statements before allowing the user input. I know how to do this normally, but I think I'm getting confused because of the array piece. Thanks much.
public static void main(String[] args) {
double[] userNumbers = printUserNums();
double average = getAverage(userNumbers);
printAverage(average, userNumbers);
}
public static double[] printUserNums() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter five to ten numbers separated by spaces: ");
double[] userNums = new double[10];
return userNums;
}
public static double getAverage(double[] userNums) {
Scanner in = new Scanner(System.in);
int counter = 0;
double average = 0.0;
double sum = 0;
for (int i = 0; i < userNums.length; i++) {
sum = sum + userNums[i];
}
if (counter != 0) {
average = sum / userNums.length;
}
return average;
}
public static void printAverage(double average, double[] userNums) {
System.out.printf("The average of the numbers " + userNums + " is %.2f", average);
}
}
You are never asking for the numbers!
You need to ask for an input from the scanner:
String inputValue = in.next();
and then split your full string (containing the numbers separated by space) using space as your regex to get the numbers:
String[] stringValues = inputValue.split("\\s+");
You should probably have some kind of checking to verify that there is at least 5 values and no more than 10 values by your requirements.
If the checking passes, just loop through your array and convert the string values to double values with Double.valueOf(String s) and store them in your double array.
It's not how I would normally get numbers from user input but if you want to have them in one go, this should work.
Related
I've been trying to get this program working for 3 days now. I've been researching on various websites and stackoverflow as well and I am just not having much success.
The goal is this program is to take in a user input that may be seperated by any amount of white space and also a single semicolon. The integers will then be added and the average will be calculated. The trick is however fractions may also be implemented and can be in the following formats : 12/33 or (12/33).
Fractions are percentage scores out of 100.
I was successfully able to eliminate whitespace and the semicolons I am just unsure how I can do the calculation aspect of this code specially dealing with the fractions.
This is my current code:
public static void main(String[] args) {
System.out.println("Enter a Set of Grades:");
Scanner messageIn = new Scanner(System.in);
String store = new String();
store = messageIn.nextLine();
store = store.trim().replaceAll(" +", "");
//store = store.trim().replaceAll("(", "");
//store = store.trim().replaceAll(")", "");
String[] dataSet = store.split(";");
//messageIn.close();
for (int i = 0; i<dataSet.length; i++) {
System.out.println(dataSet[i]);
}
}
Thank you so much for any help
I haven't gotten this far but for example this code be my input:
98;37; 12/33; (33/90); 88; 120/150;
The output would be:
The Average is: 62.67
How about something like this where you check if the individual grade contains a / and deal with that case separately:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
//Initialize scanner object
Scanner scanner = new Scanner(System.in);
//Prompt user for input
System.out.print("Enter a Set of Grades:");
String store = scanner.nextLine();
//Remove all white space and round brackets
store = store.replaceAll("[\\(\\)\\s+]","");
//Split input into individual grades
String[] grades = store.split(";");
double sum = 0;
//Loop over each entered grade and add to sum variable
for (String grade : grades) {
if(grade.contains("/")) {
double numerator = Double.parseDouble(grade.split("/")[0]);
double denominator = Double.parseDouble(grade.split("/")[1]);
sum += numerator/denominator * 100;
} else {
sum += Double.parseDouble(grade);
}
}
System.out.printf("The average is: %.2f\n", sum/grades.length);
}
}
Example Usage:
Enter a Set of Grades: 98;37; 12/33; (33/90); 88; 120/150;
The average is: 62.67
Try it out here!
So I know I have to get the remainder in order for this to work. However, it works perfectly except for the first line where it gives me 6 instead of 5 for the first line. I think this is happening because 0 is considered a multiple of 5, but I am not really sure of how to get around this. I looked at How to display 5 multiples per line? but I am having trouble seeing how to fix my code using that as it doesn't appear like they had the first line being messed up issue. For example, if I enter 17 into the positive number it gives 6 numbers for the first line and then 5 for the rest. Then it gives the remaining ones which is what I want. For the average part you can type anything as I am going to work on that later. So the format should be something like this:
4.50, 5.56, 2.73, 8.59, 7.75,
...
5.34, 3.65,
Here is my code and thanks for the help:
import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
ArrayFun a = new ArrayFun();
}
public ArrayFun() {
Scanner input = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive number: ");
int limit = input.nextInt();
// Get input from the user
System.out.print("Enter the lower bound for average: ");
double lowerBound = input.nextDouble();
// Generate an array of random scores
double[] allScores = generateRandomArrayOfScores(limit);
// Display scores, wrapped every 5 numbers with two digit precision
DecimalFormat df = new DecimalFormat("0.00");
displayArrayOfScores(allScores , df);
// Calculate the average of the scores and display it to the screen
//double average = calculateAverage(lowerBound , allScores); //
System.out.print("Average of " + limit + " scores ");
System.out.print("(dropping everything below " + df.format(lowerBound) + ") ");
//System.out.println("is " + df.format(average) );//
}
private double[] generateRandomArrayOfScores(int num) {
double[] scores=new double[num];
for (int i=0;i<scores.length;++i) {
double number=Math.random()*100.0;
scores[i]=number;
}
return scores;
}
private void displayArrayOfScores(double[] scores, DecimalFormat format) {
System.out.println("Scores:");
for (int i=0;i<scores.length;++i) {
String num=format.format(scores[i]);
if ((i%5==0)&&(i!=0)) {
System.out.println(num+", ");
}
else{
System.out.print(num+", ");
}
}
System.out.println();
}
}
The problem is indeed the 0, exactly this part (i%5==0)&&(i!=0). Replace this by i%5==4 and it should work. It is because System.out.println(...) makes the new line after printing the string and if you count 0,1,2,3,4,5 those are 6 numbers, because you treat 0 differently. The last number in the groups of 5 has a modulo of 4. (i+1)%5==0 would work too fo course, it is the equivalent. Alternatively you could do an empty System.out.println() using your condition and print the number as the others afterwards.
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.
It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?
public class AverageWithMethods {
public static void main(String[] args) {
String userNumbers = getUserNums();
double average = userNumAvg(userNumbers);
printAverage(0, userNumbers);
}
public static String getUserNums() {
Scanner in = new Scanner(System.in);
String userNumInput = "";
System.out.print("Please enter five to ten numbers separated by spaces: ");
userNumInput = in.nextLine();
return userNumInput;
}
public static double userNumAvg(String userNumInput) {
Scanner in = new Scanner(System.in);
Scanner line = new Scanner(in.nextLine());
double count = 0;
double average = 0.0;
double sum =0;
while (in.hasNextDouble()) {
count++;
sum = line.nextDouble();
}
if (count != 0) {
average = sum / count;
count = Double.parseDouble(userNumInput);
}
return average;
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);
}
}
count how many spaces there are in your string. You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String
e.g.
String fiveNums = "1 2 3 4 5";
String noSpaces = fiveNums.replace(" ", "");
System.out.println(fiveNums.length() - noSpaces.length());
From your first section of code I am making the assumption all the numbers are entered on a single line all at once.
My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?
The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.
Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
numbers++;
total += line.nextDouble();
}
line.close(); // Good habit
You can then compute your average with all this information:
double avg = total/numbers;
Notes:
Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.
I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.
When you want to understand how many numbers input the user, you can:
String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;
User input quantity numbers.
Here is one of the possible ways to do from your original code:
import java.util.Scanner;
public class GetAverage {
public GetAverage() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter five to ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new GetAverage();
}
}
OUTPUT:
Please enter five to ten numbers separated by spaces:
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50
I'm working on a program that will read a whole line of numbers and then it will display the sum. It must be written in java and it must be as simple as possible. So nothing to much harder than some arrays or what ever needed to just make it work.
This is an example of what I want:
Please enter some numbers with a space In between each.
12 34 7 93 4
This is the Sum of those numbers: 150
I have had a number of attempts and this is what I have got at the moment.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int numbers;
int total;
System.out.println("Please enter some numbers with a space between each");
numbers = kb.nextInt();
for(int i=args.length; i<numbers; i++) {
System.out.println("The sum is " + numbers);
}
}
Scanner#nextInt just reads a single int from the input stream. Instead, you want to read a bunch of numbers and start working on them.
I can think on two solutions for this:
Read the whole line (using Scanner#nextLine), split it by blank space (" ") (using String#split), convert each String into an int and calculate the sum (using Integer#parseInt).
int total = 0;
System.out.println("Please enter some numbers with a space between each");
String lineWithNumbers = kb.nexLine();
String[] numbers = lineWithNumbers.split(" ");
for (String number : numbers) {
total += Integer.parseInt(number);
}
Read the whole line (using Scanner#nextLine), use another Scanner to read the integers stored in this String and calculate the sum.
int total = 0;
System.out.println("Please enter some numbers with a space between each");
String lineWithNumbers = kb.nexLine();
Scanner lineScanner = new Scanner(lineWithNumbers);
while (lineScanner.hasNext()) {
total += lineScanner.nextInt();
}
the user must input a set of numbers of type double that we must then find the number that equalizes the numbers
here is a link to the question
https://www.dropbox.com/s/0hlps5r8anhjjd8/group.jpg
I tried to solve it myself, I did the basics, but for the actual solution I don't even know where to start ?_? any hint would be much helpful
Here my attempt:
import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int arr =1000000;
while(arr > 10000) {
System.out.println("enter number of students that are providing the money");
arr = input.nextInt(); //user input for the size of the array
}
double size[] = new double[arr]; //array creation , size based on user input
for (int i =0; i<size.length;i++) { //to input values into the array
System.out.println("enter amount of money");
size[i] = input.nextDouble(); //input values into the array
}
for(int i=0; i<size.length;i++) { //prints out the array
System.out.println(size[i]);
}
}
}
Thank you in advance
Step 1. Read the data for a test case and put it into a suitable structure. I would probably choose a double contribution[] for this assignment.
Step 2. Calculate the average contribution, avg.
Step 3. Sum up the amount of money that need to change hands. sum over abs(contribution[i]-avg). Note: Don't forget to divide the total by 2.