This is a simple java function taking an input in double. It takes an input and first check if the value is non-numeric. And then check if the value is greater than 0 or not.
The problem I am facing is every time I enter a non-numeric input, it runs an infinite loop and only print "Enter a number greater or equal to 1.0: "
double getInput(double n) {
Scanner kbd = new Scanner(System.in);
boolean flag = false;
boolean check = false;
while (!flag) {
System.out.println("Enter a number greater or equal to 1.0: ");
try {
n = kbd.nextDouble();
if (n >= 0 || n < 0)
check = true;
} catch (InputMismatchException ex) {
err.print("Invalid Data Type (not Numeric)");
}
if (check == true) {
if (n < 0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
kbd.nextDouble does not consume new line characters, hence these will be repeatedly passed into the while loop.
In your catch block instead of just throwing an exception, you can pass kbd.nextLine() so that for the next loop your input method is ready.
catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}
Here is the complete code for you:
double getInput(double n)
{
Scanner kbd = new Scanner( System.in );
boolean flag =false;
boolean check = false;
while(!flag)
{
System.out.println("Enter a number greater or equal to 1.0: ");
try
{
n = kbd.nextDouble();
if(n>=0 || n<0)check = true;
}
**catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}**
if(check==true)
{
if(n<0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
Reading a double value from the scanner wont read the end of line
n = kbd.nextDouble();
so the scanner object will have something to read unless you get the line ending calling
kbd.nextLine();
the logic point to do this exactly after the exception comes...
catch (InputMismatchException ex) {
System.err.print("Invalid Data Type (not Numeric)");
kbd.nextLine(); ///here!!!
}
Related
Just want to know if there was any better way of doing this since it's a lot of writing.
boolean isInputValid = false;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
if (input < 0 || 10 < input) {
System.out.println("Number outside of range.");
} else {
isInputValid = true;
}
} while (!isInputValid);
Well there are some things that can be ommited on a first look, but there is not much to remove.
Reduced integer parsing in a single line and removed input variable.
Change isInputValid to its negation isInputInvalid to remove else , Boolean assignment and negation in the while clause.
Moved if into the try clause to make redundant and remove the continue statement.
boolean isInputInvalid = true;
do {
System.out.print("Input: ");
try {
age = Integer.parseInt( sc.nextLine());
isInputInvalid = input < 0 || 10 < input;
if (isInputInvalid) {
System.out.println("Number outside of range.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
}
} while (isInputInvalid);
Well by first glance, I can see that you're comparing an incorrect variable type of string with an integer (your input variable), I'm just going to assume that you meant to compare the age. You should also put the if statements within your try/catch to ensure that its handled as intended (there's also no point in having it outside the try/catch if a NFE is thrown, it won't get ran anyways).
boolean isInputValid = true;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
if (age < 0 || 10 < age) {
System.out.println("Number outside of range.");
isInputValid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
} while (isInputValid);
I am trying to write a method that asks a user for a positive integer. If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value". This part is not the issue. The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.
Here is my code:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value. When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.
What you want to do is add the line
scanner.next();
in your catch clause to basically say skip over that token.
Side note: Your method in general is unnecessarily long. You can shorten it into this.
private static int nonNegativeInt() {
int value = 0;
while (true) {
try {
if ((value = scanner.nextInt()) >= 0)
return value;
System.out.println("Please enter a positive number");
} catch (InputMismatchException e) {
System.out.println("That is not a valid value");
scanner.next();
}
}
}
you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever. Adding properValue = true; or even a break statement inside the catch statement gives you the required functionality!
I hope I helped!
You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
scanner = new Scanner(System.in);
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
This is indeed nearly identical to SO: Java Scanner exception handling
Two issues:
You need a scanner.next(); in your exception handler
... AND ...
You don't really need two loops. One loop will do just fine:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
continue;
} else if (variable >= 0) {
properValue = true;
}
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
scanner.next();
}
} while (properValue == false);
return variable;
}
Just add a break statement inside your catch.
Btw, you can get rid of the while loop by rewriting it like this:
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else {
properValue = true;
}
}
//...
I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.
I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...
public static void main(String[] args)
{
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do
{
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
}
catch(InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.
I've heard that Exceptions shouldn't be used to validate user input. Why is that?
Regardless, it's not relevant to this question, as it is an exercise in Exception handling.
Without using isValid boolean variable and make simple code for input.
int arraySize = 0;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
break;// loop break when got a valid input
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
catch(Exception mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception
public static void main(String[] args) {
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = Integer.parseInt(keyboard.next());
} catch (NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
} catch (InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
} catch (NumberFormatException nfe) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
}
mmuzahid is almost there. But I added a way of checking negative number as well. Try this
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) {
System.out.println("Make sure to enter a valid positive number.");
} else {
break;
}
} catch (Exception mistake) {
System.out.println("Make sure to enter a valid number. Error:" + mistake);
}
} while (true);
Use keyboard.nextLine() and NumberFormatException
do {
// more code
try {
arraySize = Integer.valueOf((keyboard.nextLine()));
} catch (NegativeArraySizeException mistake) {
// more code
isValid = false;
} catch (InputMismatchException mistake) {
// more code
isValid = false;
} catch (NumberFormatException mistake) {
// more code
isValid = false;
}
} while (isValid == false);
I just learned about the 'try' statement in Java, and what I'm trying to do is to have this input loop until the user's input is both an integer and a positive one.
This is my code so far:
int scanning () {
Scanner scan = new Scanner(System.in);
int input = 0;
boolean loop = false;
do {
try {
System.out.print("Amount: ");
input = scan.nextInt();
if (input < 0) {
System.out.println("Error. Invalid amount entered.");
loop = true;
}
} catch (Exception e) {
System.out.println("Error: Invalid input");
loop = true;
}
} while (loop);
return input;
}
However it goes through an infinite loop when the user inputs an invalid integer, printing the error message over and over. The expected outcome is to keep asking the user for a valid input.
This code will help you to be in infinite loop and also throw a exception when input is a -ve integer.
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions.So first create a user defined exception AmountException.
public class AmountException extends Exception {
private static final long serialVersionUID = 1L;
public AmountException() {
// TODO Auto-generated constructor stub
System.out.println("Error. Invalid amount entered");
}
}
And now edit your scanning() to this :
int scanning () {
Scanner scan = new Scanner(System.in);
int input = 0;
boolean loop = false;
do {
try {
System.out.print("Amount: ");
input = scan.nextInt();
if (input < 0) {
loop = true;
throw new AmountException();
} else {
loop = false;
}
} catch (AmountException e) {
}
} while (loop);
return input;
}
Reset the value of loop variable in the do-while loop before each time just before checking the condition.
do {
try {
System.out.print("Amount: ");
input = scan.nextInt();
loop = false; // Reset the variable here.
if (input < 0) {
System.out.println("Error. Invalid amount entered.");
loop = true;
}
} catch (Exception e) {
System.out.println("Error: Invalid input");
scan.next(); // This is to consume the new line character from the previous wrong input.
loop = true;
}
} while (loop);
From you code, Change loop to false and when the valid input is given, it will terminate the while loop
boolean loop = false;
do {
try {
loop = false;
System.out.print("Amount: ");
input = scan.nextInt();
if (input < 0) {
System.out.println("Error. Invalid amount entered.");
loop = true;
}
} catch (Exception e) {
System.out.println("Error: Invalid input");
loop = true;
}
Add an else block after if, otherwise, loop will always stay true if the first input is invalid.
if (input < 0) {
System.out.println("Error. Invalid amount entered.");
loop = true;
} else {
loop = false;
}