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.
Related
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);
}
}
import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.
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);
}
Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}
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();
}
}