Terminating loops with strings. (Java) - java

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

Related

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

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

User input never enters if statement

The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);

Proper placing of the myScanner.next() method using Scanner class

Question 2:
As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int counter = 0;
int addSum = 0;
while (counter < 3) {
counter++;
int numberEntered = 0;
System.out.println("Enter number " + counter + " :");
boolean hasNextInt = myScanner.hasNextInt();
if (hasNextInt) {
numberEntered = myScanner.nextInt();
// myScanner.nextLine(); //why can't myScanner.nextLine()
// could go here right after the number entered
// is captured and stored in the numberEntered variable;
addSum = addSum + numberEntered;
} else {
System.out.println("Invalid number entered");
}
// myScanner.nextLine only works if placed here before
// closing of the while loop;
myScanner.nextLine();
}
System.out.println("The sum of the numbers entered are " + addSum);
myScanner.close();
}
}
Right now, you are always incrementing the counter no matter what:
while (counter < 3) {
counter++;
Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.
You should only increment the counter when the user enters a valid number:
if (hasNextInt) {
counter++;
numberEntered = myScanner.nextInt();
Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:
System.out.println("Enter number " + (counter + 1) + " :");

For loop to get user input lets you enter two values for the first question, but only calculates one value

I created a small program that asks the user for 10 random numbers and it will print the sum of those numbers. I embedded it with a for loop and included a counter. Everything seems to be working fine except when I run the program, the first question allows me to enter two values, but it will still only calculate a total of 10 numbers.
Below is what I currently have and I need to understand what is going wrong when it prompts the user for the number the first time:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}
In each loop, you're calling scanner.nextInt() and scanner.hasNextInt(). But you do not use the result of hasNextInt() in a meaningful way (you might have noticed that your "Invalid Number" output is not what happens if you enter something that's not a number).
The first call to nextInt() blocks until you enter a number. Then hasNextInt() will block again because the number has already been read, and you're asking whether there will be a new one. This next number is read from System.in, but you're not actually using it in this iteration (you merely asked whether it's there). Then in the next iterations, nextInt() will not block because the scanner already pulled a number from System.in and can return it immediately, so all the subsequent prompts you see actually wait for input on hasNextInt().
This amounts to 11 total input events: The firts nextInt() plus all 10 hasNextInt()s
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
// } else {
// System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
Don't call hasnextInt() it has no use here.
It has taken 11 inputs rather than 10.
If you remove this condition it will take 10 inputs and work fine.
Your condition have no impact on it.

Averaging User Input, looping input until negative number is entered

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.

Categories