WHILE Loop Condition Does Not Validate Input - java

I have a WHILEloop which checks for marks for a particular student. However, it does not loop if the value is invalid (input less than 0 and more than 100):
int marks= -1;
System.out.print("Student Marks (/100): ");
while (((marks< 0) || (marks> 100))) {
try {
marks = Integer.parseInt(sc.nextLine());
break;
} catch (NumberFormatException nfe) {
System.err.println("Error: Invalid Mark(s)");
System.out.print("Student Marks (/100): ");
}
}
It does catches exception if characters other than numbers are entered.
But it does not loop again if value if less than 0 or more than 100.
I have tried making many changes to it but to no result.
Any help given is appreciated!

You should remove the break statement, since it breaks you out of the loop regardless of what value of marks was input.

Always use continue instead of break if you want to keep the loop running.

You may check the marks inside the while loop with an if condition and here you may use break -
import java.util.Scanner;
public class TakeInput{
public static void main(String args[]){
int marks= -1;
Scanner sc = new Scanner(System.in);
System.out.print("Student Marks (/100): ");
while (sc.hasNext()) {
try {
marks = Integer.parseInt(sc.nextLine());
if(marks<0 || marks>100){
break;
}
//do something
// with the marks
//take new marks
System.out.print("Student Marks (/100): ");
} catch (NumberFormatException nfe) {
System.err.println("Error: Invalid Mark(s)");
System.out.print("Student Marks (/100): ");
}
}
}
}
Now as long as you enter anything except a number n when n<0 || n>100 will continue the loop. Any NumberFormatExeption take you to the catch block.
If you enter 34 then it goes to the while block and prompt for a next number.
Then if you enter 56 then it dose the same thing.
When you enter any String rather than a number than it goes to the catch block
This process continues until you enter a invalid number (n>100 || n<100). Pressing Ctrl+C also exit you from the loop.
Hope it will help you.
Thanks a lot.

Related

My loop with try catch is stuck in endless loop and it should prompt the user each time for an input

I'm trying to ask the user for a number and if they enter anything wrong (not an int between 1 and 99) then catch (to prevent crash if string) and loop until enter a right number. My loop is stuck in an endless loop somehow. Note: I do have the Scanner imported and the exception imported too.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String result;
int number;
boolean done = false;
while (true) {
try {
System.out.println("Please select a number from 1 to 99.");
number = input.nextInt();
input.nextLine();
if (number >= 1 || number <= 99) {
result = checkNumber(number);
System.out.println(result);
break;
}
} catch (InputMismatchException exception) {
}
}
}
input.nextInt() won't consume anything not an int. It will throw an exception. You ignore the exception and try to consume an int. It's still not an int. Same exception. Infinite loop. Add another input.nextLine() in your catch block.

Loop will not end despite the terminating expression

Hello Stack overflow community,
My prompt is:
**" You will do error checking to make sure that the hour entered is in the range [0, 23]. Keep asking the user until the user enters a time within the valid range.
My program when it has the correct integer inputs (any int input really) will work correctly. However, if i enter a non-int, then everything is stuck in an infinite loop.
What am I doing wrong?
import java.util.*;
public class Tester2 {
int a; // any valid int number
public void loop()
{
Scanner sc = new Scanner(System.in);
int x=0; // terminating int
while(x==0)
{
System.out.println("Enter 0-23: ");
try
{
if(sc.hasNextInt())
{
a=sc.nextInt();
if((a>=0&&a<=23))
{
System.out.println("Success! ");
x=1;
}
else
{
System.out.println("Retry! ");
a=0;
x=0;
}
}
}
catch (NumberFormatException ex)
{
System.out.println("invalid input");
}
}
}
}
sc.hasNextInt() will return false if the next element to be read is not a valid integer. However, this element is not read at any point in your code in that case.
You should ensure that this element is read and discarded when sc.hasNextInt() is false (adding sc.next() inside an else block should do the trick).

Exception handling with a do-while loop in Java

The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is executed, but the program runs into a infinite loop. Could someone guide me into the right direction, I appreciate the help. :-D
package chapter_08;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class IntegerList {
static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 1;
int inputNum;
do {
System.out.print("Type " + counter + " integer: " );
try {
inputNum = input.nextInt();
numbers.add(inputNum);
counter += 1;
}
catch (Exception exc) {
System.out.println("invalid number");
}
} while (!(numbers.size() == 3));
}
}
That is because when the next int is read using nextInt() and it fails, the Scanner still contains the typed contents. Then, when re-entering the do-while loop, input.nextInt() tries to parse it again with the same contents.
You need to 'flush' the Scanner contents with nextLine():
catch (Exception exc) {
input.nextLine();
System.out.println("invalid number");
}
Notes:
You can remove the counter variable, because you're not using it. Otherwise, you could replace counter += 1 by counter++.
You can replace while (!(numbers.size() == 3)) with while (numbers.size() != 3), or even better: while (numbers.size() < 3).
When catching exceptions, you should be as specific as possible, unless you have a very good reason to do otherwise. Exception should be replaced by InputMismatchException in your case.
If inputNum = input.nextInt(); cannot be fit into an int and a InputMismatchException is raised, the input of the Scanner is not consumed.
So after the catch, it loops and it goes again here :
inputNum = input.nextInt();
with exactly the same content in the input.
So you should execute input.nextLine(); in the catch statement to discard the current input and allow a new input from the user.
Besides it makes more sense to catch InputMismatchException rather than Exception as other exception with no relation with a mismatch could occur and it would not be useful to display to the user "invalid number " if it is not the issue :
catch (InputMismatchException e){
System.out.println("invalid number ");
input.nextLine();
}
You should to use a break; in your catch(){} like so :
try {
inputNum = input.nextInt();
numbers.add(inputNum);
counter += 1;
} catch (Exception e) {
System.out.println("invalid number ");
break;
}
So if one input is not correct break your loop.
try changing
inputNum = input.nextInt();
to
String inputText=input.next();
inputNum = Integer.valueOf(inputText);
it works perfectly well.
You need to move the scanner to the next line. Add this line of code below the error message in the catch section.
input.nextLine();

Scaner nextInt() - Shall I handle the InputMismatchException thrown by this method when user enters something other than integer?

While using the nextInt() method of Scanner class, if InputMismatchException is being thrown, shall I handle that by catch block ?
It's a runtime exception, but caused by user input and not programmer's mistake.
Here is my code.
package com.sample.programs;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ScannerPractice {
public static void main(String[] args) {
readInteger();
}
private static void readInteger() {
// Created a Scanner object
Scanner input = new Scanner(System.in);
// Display a prompt text
System.out.println("Please enter an integer");
// Accept the input from user
int number;
try {
number = input.nextInt();
// Display the output to user
System.out.println("You entered: " + number);
} catch (InputMismatchException exception) {
System.err.println("You have entered wrong input. Please enter a number");
// Log the stack trace
readInteger();
} finally {
input.close();
}
}
}
Yes. Is better to handle the user wrong input beacouse you cannot control or be sure that the user will aligned data correctly, and you cannot read doubles, or strings with readInteger().
So I will handle the exception.
Regards.
No, you should call hasNextInt() before calling nextInt().
The exception truly means programmer error, since the programmer forgot to check validity before calling the method.
If you then want to prompt the user again, remember to discard the bad input first.
Scanner input = new Scanner(System.in);
int value;
for (;;) {
System.out.println("Enter number between 1 and 10:");
if (! input.hasNextInt()) {
System.out.println("** Not a number");
input.nextLine(); // discard bad input
continue; // prompt again
}
value = input.nextInt();
if (value < 1 || value > 10) {
System.out.println("** Number must be between 1 and 10");
input.nextLine(); // discard any bad input following number
continue; // prompt again
}
if (! input.nextLine().trim().isEmpty()) {
System.out.println("** Bad input found after number");
continue; // prompt again
}
break; // we got good value
}
// use value here
// don't close input

Try-Catch inside While Loop

The code below asks the user how many racers he/she would like.
while (true) { // loops forever until break
try { // checks code for exceptions
System.out.println("How many racers should" + " participate in the race?");
amountRacers = in.nextInt();
break; // if no exceptions breaks out of loop
}
catch (InputMismatchException e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
continue; // continues to loop if exception is found
}
}
If a number is entered at amoutnRacers = in.nextInt(); the code breaks out of the loop and the rest of the program runs fine; however, when I enter something such as "awredsf" it should catch that exception, which it does. Instead of prompting the user again it loops continuously, which to me does not make sense.
The program prints like this when looping continuously:
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?
How many racers should participate in the race?Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
Please enter a number! null
...
I do not understand what is going on amountRacers = in.nextInt(); so why is the user not able to enter a number?
Just add input.next() once you catch InputMismatchException.
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
input.next(); // clear scanner wrong input
continue; // continues to loop if exception is found
}
You need to clear the wrong input, which scanner automatically does not.
Today i solved this problem :-) This is my code. I think that i help
public int choice () throws Exception{
Scanner read = new Scanner(System.in));
System.out.println("Choose the option from the upper list");
int auxiliaryChoiceMenu = 5;
int auxiliaryVariable = -1;
boolean auxiliaryBoolean = false;
while (!auxiliaryBoolean) {
try {
auxiliaryVariable = read.nextInt();
read.nextLine();
} catch (Exception e) {
System.out.println("incorrect data, try again"+e);
read.nextLine();
continue;
}
if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
System.out.println("incorrect data, try again");
} else {
auxiliaryBoolean = true;
}
choiceMenu = auxiliaryVariable;
}
return choiceMenu;
//choicemenu is a external variable
}
You may need to create a Scanner class for getting standard input streamed from the keyboard. You should have a statement somewhere in your code that creates an instance of a Scanner class like: Scanner in = new Scanner(System.in);
so the " in " variable in your statement: amountRacers = in.nextInt(); waits and scans for entered input from the keyboard and stores it.
Why use a loop with a try and catch?
My advice would be to always use a try and catch with either a while or do while loop, so you can ask the user to repeat his/her input. It also depends which loop you already use and/or on how your code is structured.
For example if you already have a do while loop then I would advice you to simply adjust/modify your existing loop.
I will post some examples on how you can use a try and catch with a loop to repeat the input after a user has provided a wrong one.
See examples below:
Example 1
Scanner input = new Scanner(System.in);
int exampleInput = 0;
do {
try {
System.out.print("\nEnter an integer from 1 to 25: ");
exampleInput = input.nextInt();
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer from 1 to 25");
input.next(); // Clear scanner buffer of wrong input
}
} while (exampleInput < 1 || exampleInput > 25);
System.out.println("Print exampleInput: " + exampleInput);
Example 2
Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDone = false;
do {
try {
System.out.print("\nEnter an integer: ");
exampleInput = input.nextInt();
isDone = true;
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer");
input.next(); // Clear scanner buffer of wrong input
}
} while (!isDone);
System.out.println("Print exampleInput: " + exampleInput);
Example 3
Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDoneLoop2 = false;
while (!isDoneLoop2) {
try {
System.out.print("\nEnter an integer: ");
exampleInput = input.nextInt();
isDoneLoop2 = true;
}
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Wrong input! Enter an integer");
input.next(); // Clear scanner buffer of wrong input
}
}
System.out.println("Print exampleInput: " + exampleInput);
This works for me.
while (true) {
try {
System.out.print("Ingrese la cantidad de puestos de atenciĆ³n: ");
int puestos = Integer.parseInt(scn.nextLine());
break;
}
catch (NumberFormatException e) {
System.out.println("Ingrese un valor correcto");
scn.reset();
continue;
}
}

Categories