How to read a line of numbers and display the sum? - java

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();
}

Related

Calculating Average, A String Tokenization Exercise

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!

Java-How to Display Numbers 5 Times Before a New Line

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.

Calculate Average with Arrays from User Input

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.

Calculate an Average from user input of five to ten numbers using Methods

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

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources