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!
Related
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.
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();
}
I am using Java eclipse and I would like to have the user input the filename to retrieve a list of scores from the file. My goal is to take the average of those numbers. What line of code do I need just to get the user to input a file name and for the program to take those numbers so that I can compute with them? Currently I can have the user input scores, But I need to get the numbers from the file instead. I have visited numerous resources on this site. Here are a few:
BufferedReader, Error finding file, Getting a list from a file
package Average;
/**An average of scores*/
import java.util.Scanner;
public class Average2 {
public static void main(String[] args) {
int grade = 0;
int students = 0;
float total = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
students = input.nextInt();
if (students <= 10) {
System.out.println("Enter the grades of the students: ");
for(int i = 0; i < students; i++) {
do {
grade = input.nextInt();
} while(grade < 0 || grade > 100);
total += grade;
}
average = (total/students);
int median = ((82+84)/2);
System.out.println("The average is " + average);
System.out.println("The mean is " + median);
}
}
}
Update since above post!
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = 0;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println(sum);
}
}
The results I get from this:
Enter filename:
esp.txt <--entered by me
501.0
Given that you want to find the average of numbers in a file, you could do something like this:
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// Initialize our relevant counters
double sum = 0.0;
int numStudents = 0;
// While there is still stuff in the file...
while (fileToRead.hasNext()) {
// Is this next line consisting of just a number?
if (fileToRead.hasNextDouble()) {
// If it is, accumulate
sum += fileToRead.nextDouble();
numStudents++;
}
else { // Else, just skip to the next line
fileToRead.next();
}
}
// Close the file when finished
fileToRead.close();
// Print the average:
System.out.println("The average mark is: " + (sum / numStudents));
This code will create a new Scanner object that will read input from your keyboard. Once it does that, you type in the file name, and it gets access to this file by opening another Scanner object. After that, we initialize some counters to help us calculate the average. These are sum, which will add up all of the marks we encounter and numStudents, which keeps track of how many students there are in the file.
The while loop will keep looping through each line of this file until it reaches the end. What is important is that you check to see whether or not the line you are reading in next consists of a single number (double). If it is, then add this to our sum. If it isn't, skip to the next line.
Once you're finished, close the file, then display the average by taking the sum and dividing by the total number of students we have encountered when reading the numbers in the file.
Just took a look at your profile and your profile message. You have a long road ahead of you. Good luck!
Look at the Java tutorial on Scanning: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html, particularly the ScanSum example. It shows how to scan double values from a text file and add them. You should be able to modify this example for your project.
Scanner userInput = new Scanner(System.in);
System.out.println("ENter filename");
String fileName = userInput.next();
Scanner fileScan = new Scanner(new File(fileName));
then use scanner methods to process lines or string tokens you are interested in.
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.