Java infinite loop, while validation [duplicate] - java

This question already has an answer here:
Exception handling infinite loop
(1 answer)
Closed 5 years ago.
This is a part of my code which is used to validate an input and loop if it is a character, however it causes an infinite loop when a character is input, but works fine when an integer is used. I don't know whats causing the infinite loop but any help would be appreciated.
System.out.println("Please type in a mark and enter -1 to end the program");
while (mark != -1) {
if (in.hasNextInt()) {
mark = in.nextInt();
}
else {
System.out.println("Please input an integer: ");
}

If you input a character the:
if (in.hasNextInt())
Will return false, and you go to the else, when it loops, the in.hasNextInt() is still false entering the else and looping forever.

Related

how can you repeat a statement if a condition is not reached in java [duplicate]

This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 2 years ago.
I'm trying to make a program that asks you to input some data as a string then if the string is more than 6 characters long it will ask you to do it again until you input an answer with less than 6 characters then moves on to the next question, how can i do this?
You can do it without a break, using a boolean variable.
boolean flag = true;
String answer;
while(flag){
System.out.println("Enter a string with less than 6 characters:");
answer = input.nextLine();
if(answer.length() > 6){
System.out.println(answer + " has more than 6 characters. Please try again!");
}else {
flag = false;
}
}
I would recommend using a while loop that is always true, then break when condition is met.
while (true) {
System.out.println("Enter answer: ");
String answer = sc.nextline();
if(!answer.length() > 6) {
// do stuf
break;
}
}

fixing the java.util.InputMismatchException on second step of nextInt() [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 4 years ago.
I'm writing a very simple program and where I am getting 3 ints from a user and want to check to make sure they are all ints before storing them into seperate variables to process. The check I've used works on the first input but fails and throws the exception on the second two.
boolean properInt = scanner.hasNextInt();
int largest = Integer.MAX_VALUE;
boolean anError = false;
while(properInt=false){
anError=true;
System.out.println("Invalid number...whole numeric values only");
}
while(properInt =true){
int a= scanner.nextInt();
System.out.println("you entered "+ a);
int b = scanner.nextInt();
System.out.println("you entered "+ b);
int c= scanner.nextInt();
System.out.println("you entered "+ c);
}
Reason is when you use any of the nextXxx(...), the scanner cursor is reset to where it was before the call. When you press 'enter' key after entering a valid number, scanner ignores the 'character' (enter). However, when you enter an invalid value, an exception is thrown and the enter key character is seen by the next 'nextInt' as another condition and so won't work.
I would suggest using nextLine and then Integer.ParseInt and catching NumberFormatException.
Also, your while loop check is incorrect.
properInt=false is a statement.
while(properInt==false) is a condition..
English is not my strength so if its confusing let me know.

hasNext() of Scanner keeps looping [duplicate]

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.

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.

Try catch block causing infinite loop? [duplicate]

This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.
And yes, I am new to Java
nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().
Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.
Try using
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
try{
//let user know you are now asking for a number, don't just leave empty console
System.out.println("Please enter a number: ");
String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
//test if user entered a number in that line
int number=Integer.parseInt(lineEntered);
System.out.println("You entered a number: "+number);
isInValidResponse = false;
}
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
catch (Exception e){
System.out.println("I did not understand what you said. Try again: ");
}
}
Because of common topic of avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/

Categories