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);
Related
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 am trying to learn try-catch uses and have to validate input so that the user must enter 1 or 2 for the program to continue. I believe I am close, but cannot seem to get the program to continue if the user enters something wrong such as '3' or '2.12'.
Here's what I have:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
I don't necessarily see the point of using InputMismatchException for your use case. Instead, if the input doesn't match what you expect, you can log an error and just prompt the user to input again.
But [Integer#parseInt()][1] can throw an exception if the input isn't an actual integer. In your original code you never actually use the result of this call, but I have done so in my answer. In this case, it does potentially make sense to use a try-catch block.
int result;
while (true) {
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
result = Integer.parseInt(input);
} catch(Exception e) {
System.out.println("Could not parse input, please try again.");
continue;
}
if (result != 1 && result != 2) {
System.out.println("Invalid input! Please select '1' or '2':");
}
else {
break;
}
}
You should put in your condition the throw statement in able to your catch statement fetch the error, the code should be like this:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
throw new InputMismatchException ();
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
The code is expecting for positive integers but can input string and loop again until got a positive integer input value.
Scanner scanner = new Scanner(System.in);
Integer expectedOutput = -1;
public Integer getInputNumber(){
boolean valid;
String inputData;
do {
System.out.print("Enter Input Number: \t");
try {
inputData = scanner.nextLine();
// expecting positive integers
if (Integer.parseInt(inputData) > 0) {
expectedOutput = Integer.parseInt(inputData);
valid = true;
} else {
System.out.println("Invalid Input!");
valid = false;
}
} catch (Exception ex){
valid = false;
}
} while(!valid);
return expectedOutput;}
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!!!
}
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;
}
I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}