I have a program but I dont know specifically what my mistake is or how to fix it: The question is:
Write a program that asks the user to enter a series of numbers separated by commas.
The program should calculate and display the sum of all the numbers.
For example, if I enter 4,5,6,7, the sum displayed should be 22.
This is what I have so far:
import java.util.Scanner;
public class SumAll {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userNumber;
String sum = null;
//get numbers from user and store
System.out.println("Enter numbers seperated by coma's: ");
userNumber = keyboard.nextLine();
String[] tokens = userNumber.split("[, ]");
for (int i = 0; i < tokens.length; i++) {
sum = tokens.length[i++]; //showing me error here. Its written array required but int //found.
}
System.out.println("Sum is: " + sum);
}
}
Thank you very much for the help.
Sum should be an int
int sum = 0;
Your for loop should be
for (int i = 0; i < tokens.length; i++) {
sum += Integer.parseInt(tokens[i]);
}
Because it should be:
sum += Integer.parseInt(tokens[i]);
There are several things wrong with this one line of code.
sum = tokens.length[i++];
You can't index the length of the array like that. Just index the array (see below).
The for loop is already incrementing i. You don't need to do it again.
You need to convert the token to an integer before you can add it to the sum.
You need to add the new value to the sum, not replace the old sum.
Try this instead:
sum += Integer.parseInt(tokens[i]);
You'll also need to make sum an integer. Instead of
String sum = null;
you need
int sum = 0;
I know I am more than 2 years late but I started learning Java not too long ago and would like to share my solution. :) I used the StringTokenizer class. I hope this helps someone out there in 2017 and onward.
import java.util.Scanner;
import java.util.StringTokenizer;
public class SumOfNumbersInString {
public static void main(String[] args) {
// Create a Scanner object
Scanner keyboard = new Scanner(System.in);
// Get user input
System.out.print("Enter a series of numbers seperated by commas\n> ");
String input = keyboard.nextLine();
// Display sum by calling the getSum method
System.out.println("SUM: " + getSum(input));
}
/**
*
* #param input with the format --> (#,#,#,#)
* #return sum of numbers in the input
*/
public static int getSum(String input) {
// Declare and initialize the sum accumulator variable
int sum = 0;
// Create a StringTokenizer object
// The string to be tokenized is passed as 1st parameter
// The "," that separates tokens/numbers is the 2nd parameter
StringTokenizer stringTokenizer = new StringTokenizer(input, ",");
// The hasMoreTokens method of the StringTokenizer class returns true if there are more tokens left in the string
// Otherwise, it returns false
while (stringTokenizer.hasMoreTokens()) {
// While the string has another token (number), parse the number to an integer and add its value to sum
sum += Integer.parseInt(stringTokenizer.nextToken());
}
// Return sum's value to the method call
return sum;
}
}
OUTPUT
Enter a series of numbers seperated by commas
> 4,5,6,7
SUM: 22
/** #author Jerry Urena **/
public static void main(String[] args)
{
String userinput;
int total = 0;
//keyboard function
Scanner keyboard = new Scanner(System.in);
//Ask for input
System.out.print("Please enter a series of numbers separated by commas " );
//Get user input
userinput = keyboard.nextLine();
//Split numbers
String[] numbers = userinput.split("[,]");
//String loop
for (String number : numbers)
{
//Sum of numbers
total += Integer.parseInt(number);
}
//Print results
System.out.println("Total: " + total);
}
Related
I need help with an assignment. There are many similar questions on here, but those answers are not working for me so I don't know what I'm doing wrong.
The assignment is "The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the program calculates the average of those numbers, and displays the numbers and their average to the user."
We need to call to different methods to do this. The part that's giving me problems is converting the String to doubles and finding the average. We also need to validate that there are between 5-10 numbers in the String (I can validate it once I get it to count properly). I've tried a few things, including answers to similar questions on here (shown in code below), but the only output I get is 0.0.
Here is my code:
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.next();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
Thank you so much for any help!
It seems you have an error in your main method and need to set the getNumbers equal to the getNumbers method and the same with the calcaverage double with the calcaverage method.
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
should be
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers =getNumbers();
calcAverage =calcAverage(getNumbers);
System.out.println(calcAverage);
}
You can use streams to make it more readable and avoid and external iterations
import static java.util.Arrays.stream;
import java.util.OptionalDouble;
class Scratch {
public static void main(String[] args) {
OptionalDouble optAvg = calcAverage("2 5 6 7 8 9 0 1");
if (optAvg.isPresent()) {
System.out.println("optAvg.getAsDouble() = " + optAvg.getAsDouble());
}
}
public static OptionalDouble calcAverage(String userNumbers) {
String[] inputArr = userNumbers.split(" ");
int count = inputArr.length;
System.out.println("count = " + count);
if (count < 5 || count > 10) {
throw new IllegalArgumentException("Or do some other this here!");
}
return stream(inputArr)
.mapToDouble(
Double::parseDouble) // throws a NumberFormatException if it can't convert to Double
.average();
}
}
Or even simpler
import static java.util.Arrays.stream;
import java.util.DoubleSummaryStatistics;
class Scratch {
public static void main(String[] args) {
DoubleSummaryStatistics doubleSummaryStatistics = calcAverage("2 5 6 7 8 9 0 1");
System.out.println("count = " + doubleSummaryStatistics.getCount());
System.out.println("average = " + doubleSummaryStatistics.getAverage());
}
public static DoubleSummaryStatistics calcAverage(String userNumbers) {
return stream(userNumbers.split(" "))
.mapToDouble(Double::parseDouble)
.summaryStatistics();
}
}
Here you go:
public static void main(String[] args) {
String numberString = getNumbers();
double averageNum = calcAverage(numberString);
System.out.println(averageNum);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.nextLine();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
A few changes, but you had it right for the most part. Going from the top of the file:
Removed getNumbers and calcAverage
Added numberString and averageNum (when you call functions with return, you need to store the value that it returns into a variable)
changed line:
String getNumbers = scnr.next();
to:
String getNumbers = scnr.nextLine();
Let me know if you have any questions.
Here is one way to do it with supplied values validation :
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNext()) {
String val = str.next();
// Is the supplied numerical value valid?
if (!val.matches("-?\\d+(\\.\\d+)?")) {
//No...
System.out.println("Supplied value of " + val +
" is ignored since it is not a valid numerical value!");
continue;
}
count++; // count now that we know the value is indeed valid.
i += Double.parseDouble(val);
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
Since you are processing a supplied whitespace delimited string of hopefully numerical values you can merely utilize the the Scanner#hasNext() method in conjunction with the Scanner#next() method.
Preparing the Scanner object:
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
Here we take the string contained within the supplied userNumbers string variable and trim off any possible leading and trailing white-spaces, we don't want these if there are any. We also replace any portion of the supplied string that may contain more than a single whitespace with just a single whitespace. We want to enforce this format before we proceed so as to help with eliminating any possible type of conflict later on in method code. You can't always rely on the User to provide everything perfectly all the time so if you can help then it's worth it.
Retrieving each supplied value from the supplied String:
while (str.hasNext()) {
String val = str.next();
// ... other code ...
}
The hasNext() method will allow the loop to continue for as long as there is another whitespace delimited string token to process. In this case we're hoping that each token will be a string representation of a numerical value.
Because the hasNext() method has let us get this far into the loop we know there is another String token available. The str.next() call retrieves that available token and in this case, is placing that string token into the string variable named val. This is done upon each iteration of the while loop until there are no more tokens remaining to process.
Validating a retrieved string token:
if (!val.matches("-?\\d+(\\.\\d+)?")) { ... }
Validation of each string token is done here utilizing the String#matches() method along with a specific Regular Expression (regex) of "-?\\d+(\\.\\d+)?". When passed in the matches() method, this regex checks to see if the string it is played against is indeed a string representation of a signed or unsigned integer or floating point numerical value:
-? Optional. Value is prefixed with '-'.
\\d+ One or more digits.
(\\.\\d+)? Optional. Value is post-fixed with a decimal point
and one or more digits.
In this case we're checking to see if the token is invalid and if it is we supply a message to the console window indicating as such and the fact that this token value will be ignored. We ignore it by using the continue keyword which forces the while loop into it's next iteration and bypassing the remaining code within the loop.
Converting a String numerical value to a Double data type:
count++; // count now that we know the value is indeed valid.
i+= Double.parseDouble(val);
We do the count after knowing the value provided is indeed valid. i was previously declared as a double type and sums the token numerical value after it is converted to double with the Double.parseDouble() method. Using i += is the very same as i = i +.
Another shorter way:
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNextDouble()) {
double val = str.nextDouble();
count++;
i+= val;
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
In the following code i marked the line that doesn't work.
Can someone explain me why this doesn't work?
import java.util.Scanner;
public class ArrayLength {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Please enter the array : ");
double[] userArray = myScanner.nextDouble();//This line doesn't work
}
}
I guess you are trying to set a double array from a line-separated input. If so, you could use something like this:
Scanner myScanner = new Scanner(System.in);
System.out.println("Please enter the array : ");
String strScan = myScanner.nextLine();
String[] aScan = strScan.split(" ");
double[] userArray = new double[aScan.length];
int i = 0 ;
for (String str : aScan) {
userArray[i] = Double.parseDouble(str);
i++;
}
If you are expecting the user input to be located on exactly one line and you are sure that all the values (separated by a whitespace) could be parsed as Double I do recommend using the following statement:
double[] userArray = Arrays.stream(myScanner.nextLine().split(" "))
.mapToDouble(Double::parseDouble)
.toArray();
Read whole next line as string, split it by whitespace, and then do parse each value into double.
If you only need to read a single double value and you are required to store it into an array then you could simply use the Array Initializer like this:
double[] userArray = {myScanner.nextDouble()};
This way userArray will have 1 element in total and it's first and only value will be the user input.
You have to define array index in int, then only get double input
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Decide array length
System.out.print("Please enter the array : ");
int num = Integer.parseInt(scan.nextLine());
//Create a double array to store values
double userArray[] = new double[num];
for (int i = 0; i < userArray.length; i++) {
System.out.print("Enter value " + (i + 1) + " : ");
userArray[i] = scan.nextDouble(); // you can store input with double datatype now
}
//Now display one by one
for (int i = 0; i < userArray.length; i++) {
System.out.print("Value are " + (i + 1) + " : ");
System.out.print(userArray[i] + "\n");
}
}
}
If you don't want to take input as array
double num= myScanner.nextDouble();
myScanner.nextDouble() will output a single double instead of an array of doubles. So you would need to set that double equal to a specific index in the array instead of trying to set the whole array equal to a single double. I would suggest utilizing a for loop if you want to accept multiple doubles into the array.
For Example:
for(int x = 0; x < userArray.length; x++)
{
userArray[x] = myScanner.nextDouble(); // x in this scenario is a specific position in the array
}
Also if the user input is formatted with a space between each double (i.e. 1.0 2.0 3.0 4.0 etc) myScanner.nextDouble(); will take the first double then go through the for loop again and take the next double etc. This is useful because the user input can all be on one line so the user can input the entire array at once.
I am attempting to calculate the average word length of user input in Java in a very simplistic way. The actual "math" of the code I've already completed, and it seems to be working quite well, but there are some odd house keeping things I need to address in order to complete the code.
So far, I have the following:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
}
}
}
The end result output should look like this:
run:
Please type some words, then press enter:
this is a test
Average word length = 2.75
BUILD SUCCESSFUL (total time: 10 seconds)
However, the output is looking like this:
run:
Please type some words, then press enter:
this is a test
Average word length = 4.0
Average word length = 3.0
Average word length = 2.3333333333333335
Average word length = 2.75
Based on the code that I've written, how can I change it so that:
The "average word length" is only printed one final time.
The program ends after the user presses enter
Thank you for any suggestions.
You're calculating the average every single time you enter a word, which is not what you want. Also, the while loop will continue even if enter is pressed. Try this:
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
int count = 0;
double sum = 0;
String input = sc.nextLine();
String[] words = input.split("\\s+"); // split by whitespace
// iterate over each word and update the stats
for (String word : words) {
double wordLength = word.length();
sum += wordLength;
count++;
}
// calculate the average at the end
double average = 0;
if (count > 0) {
average = sum / count;
}
System.out.println("Average word length = " + average);
Output:
Please type some words, then press enter:
this is a test
Average word length = 2.75
You just need to move your System.out.println after the loop and declare average out of the loop to prevent scope issues. However, it is more elegant to do it this way :
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
double average = 0;
for (String word : sc.nextLine().split("\\s+"))
average += word.length();
average /= words.length;
System.out.println("Average word length = " + average);
sc.close();
}
}
sc.nextLine() returns the entire line typed by the user (without the last "\n" character) and split("\\s+") splits this line using the regex \s+, returning an array containing the words. This regex means to split around any non-empty sequence of blank characters.
Just get System.out.println(...) out of the while loop. And declare average variable before the loop body.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String words = sc.nextLine();
int count = 0;
double sum = 0;
double average = 0;
sc = new Scanner(words);
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
}
}
System.out.println("Average word length = " + average);
}
A) Print your output outside of the loop when all of the averaging has already been done
B) Use Date.getTime() to get the time at the start of the program after the user has inputted their sentence, and store it in a variable, then at the end of the program, get the time again, subtract it from the old time, and divide by 1000 to convert it from milliseconds to seconds. After that you can just print it out however you want it formatted
C) call sc.readLine() after you have outputted everything so that when they press enter that line will stop blocking and let the program end.
Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}