hasNext() of Scanner keeps looping [duplicate] - java

This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?

That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.

Related

How to end do while loop with user input with if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}

Simple Palindrome [duplicate]

This question already has an answer here:
Simple Palindrome Detector [duplicate]
(1 answer)
Closed 4 years ago.
I've tried different approaches to do this, and when I do this..
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int number = in .nextInt();
int first = number
int middle = 0;
int last = first;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
it spits out "this is a palindrome". Mind you I can't use loops. Shouldn't this work?
It works when I do this...
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int first = 1;
int middle = 0;
int last = 5;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
It tells me if it's a palindrome or not...
So, it works on my end, but not the users end.
What am I missing
The problem is, you are assigning the value of the input to your variable first then you assigned the value of first to the variable last. You declared your boolean as isPalindrome = first==last (true) which will always be true in this scenario that's why you get "This is a palindrome". On your second block of code which you said "works" is because you declared first = 1 and last = 5, when you did isPalindrome = first==last (false) the value of the palindrome will always be false hence you get "This is not a palindrome" output.
I think what you need to do is rewrite your logic so you can elaborate the process you want to do. Feel free to ask a follow-up question.
In the first one, the user enters a number which is assigned to first, then you set last to be a reference to first. Since the truth value of isPalindrome depends on whether last == first, it will always be true, since you coded it that way. However, this doesn't actually prove that the number is a palindrome, because for example if the user enters the number 56, the number 56056 is not a palindrome (reverse is 65065).
In the second program, first is always 1 and last is always 5, so since they are never equivalent the condition last == first will always be false.
What are you attempting to achieve with the programs? Neither one tests the user input to be a palindrome. Try writing psuedocode first, in the comments if you like.

While loop breaks after bufferedInput change [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm doing some basic homework, and it's honestly all stuff I know. But I decided to jazz it up a little, and something I'm missing is causing an unexpected error.
The idea is to use a while loop which asks if the user would like to do something. So long as they say yes, the loop continues the operations that it holds (in this case rounding a decimal to an int). However, as soon as I enter yes, or anything really, the loop breaks there and won't continue on to the rounding portion.
public class DecimalRounder {
//Main class method that starts and ends the program. It is prepared to throw an IO exception if need be.
public static void main(String args[])throws IOException
{
//Main initializes a new reader to take input from System.in
InputStreamReader rawInput = new InputStreamReader(System.in);
//Main then initializes a new buffer to buffer the input from System.in
BufferedReader bufferedInput = new BufferedReader(rawInput);
//Main initializes other used variable
double castInput = 0.0;
String contin = "yes";
//Program then sets up loop to allow user to round numbers till content
while (contin == "yes")
{
//Program asks user if they'd like to round.
System.out.println("Would you like to round? Type yes to continue... ");
contin = bufferedInput.readLine();
//If user says yes, rounding begins. ERROR FOUND HERE?
if (contin == "yes") //INPUT "yes" DOESN'T MATCH?
{
//Program then requests a decimal number
System.out.println("Please enter a decimal number for rounding: ");
String givenLine = bufferedInput.readLine();
//rawInput is worked on using a try catch statement
try {
//givenLine is first parsed from String into double.
castInput = Double.parseDouble(givenLine);
//castInput is then rounded and outputted to the console
System.out.println("Rounded number is... " + Math.round(castInput));
//Branch then ends restarting loop.
}catch(Exception e){
//If the data entered cannot be cast into a double, an error is given
System.err.println("That is not a roundable number: " + e.getMessage());
//And branch ends restarting loop.
}
}
}
System.out.println("Have a nice day!");
}
}
Use .equals instead of == to compare strings in JAVA.
Try this :
contin.equals("yes")

Java Do While statement looping infinitely after Try Catch statement [duplicate]

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am currently working on some Java code in Eclipse and trying to use a try-catch statement inside of a do-while statement. My current code is as follows:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class GG_HighLowInvalid{
public static void main(String[] args){
Scanner cg = new Scanner(System.in);
//Assign and define variables
int guess, rand;
guess = 0;
rand = 10;
//Create loop
do
try{
guess = 0;
//Ask for a guess
System.out.print("Enter your guess: ");
//Record the guess
guess = cg.nextInt();
}
catch(InputMismatchException exception){
System.out.println("Your guess must be an integer.");
}
while (guess != rand);
}
}
When I put in any number, the code works fine and will loop to ask for another input and when 10 is entered, the code stops as it is supposed to (because guess becomes equal to rand). However, if I put in anything that is not an integer (such as "No"), an infinite loop occurs where the output prints the following:
"Your guess must be and integer."
"Enter your Guess: Your guess must be an integer."
"Enter your Guess: Your guess must be an integer."
"Enter your Guess: Your guess must be an integer."
repeating forever until the program is externally terminated.
Since the while statement is (guess != rand), why is a non-integer causing this infinite loop? Shouldn't the manual input under the try-statement be called again? Any assistance in understanding this would be greatly appreciated. Also, I am pretty new to Java, so sorry in advance if I am having simple issues.
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
Currently, your Scanner is not moving ahead to read the next input but reading the same continuously. You have to explicitly call some method which can read this incorrect value which was not expected. For example, scanner.next() call in catch block can avoid this infinite loop.
Use the following code:
catch(InputMismatchException exception){
cg.next();
System.out.println("Your guess must be an integer.");
}
After you have unsuccessfully read buffer its value isn't emptied and next time when it came to cg.nextInt() it tries to read same wrong value, and you went to loop. You need "to empty buffer", so next time it will read correct value.
You dont need to use a try catch statement. You just have to check if it is an integer or not with the hasNextInt() method of your object scanner. This is an example, it will solve your problem:
public static void main(String[] args) {
Scanner cg = new Scanner(System.in);
boolean valid = false;
//Assign and define variables
int guess, rand;
guess = 0;
rand = 10;
//Create loop
do{
System.out.println("Enter your guess: ");
if(cg.hasNextInt()){
guess = cg.nextInt();
valid = true;
}else{
System.out.println("Your guess must be an integer.");
cg.next();
}
}while (!valid || guess != rand);
}
Try resetting your variable "guess = 0" in catch block.

try statement not being used on second illiteration of loop [duplicate]

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am making a method in order to get how many numbers the user wants to sum together. aka if they want to sum the numbers 1 2 and 3. they would want to sum 3 numbers together. So when i ask them how many they want to sum together, I use a try - catch in order to catch if they enter a decimal place. Because you cant add together 3.5 numbers you can add 3 numbers or 4. problem is if the user enters a decimal, the program will infinite loop run everything but what is in the try statement. How can i fix this?
Here is the code for the method:
private static int requestMaxInputForFloat(Scanner scanner){
boolean appropriateAnswer = true; // assume appropriate catch not appropriate to loop again
int howManyInputs = 1000000; // hold value to return how many inputs. if this value we will not run.
//request an appropriate number of inputs until appropriate answer = true;
do
{
appropriateAnswer = true; //if looped again reset value to true
try{
System.out.print("How many decimal place numbers would you like to sum? ");
howManyInputs = scanner.nextInt();
}catch(Exception e){
System.out.println("Sorry but you can only request to average a whole number set of data.\nTry Again.");
appropriateAnswer = false;
}//end of try-catch
if (howManyInputs <= 0) //invalid answer
{
System.out.println("Sorry but " + howManyInputs + " is equal to or below 0. Please try again.");
}else{
appropriateAnswer = false;
}
}while(!appropriateAnswer);//end of while loop
return howManyInputs; //return the value
}// end of getMaxInput
Add scanner.nextLine(); in the catch block. I think the problem is that if nextInt() gets an error, the scanner's "pointer" is still pointing at a bad character, and if you just try nextInt() again, it will try to scan the same bad character over again. You have to do something to make the scanner skip over it. Here, you want to just throw away whatever the user typed in, so nextLine(), which skips over the entire remainder of the input line, is the most appropriate.
One other thing: I'd change
if (howManyInputs <= 0) //invalid answer
to
if (appropriateAnswer && howManyInputs <= 0) //invalid answer
Otherwise, if the user types in -1, then the loop will go back and howManyInputs will still be -1; then if the user types 3.5, you'll get the exception but you'll get a second error message because howManyInputs is still -1 left over from the previous loop. You don't need to test howManyInputs if you already know there was an input error.

Categories