Do while loop for catching exceptions in Java - java

Java beginner here. Im trying to create a do while loop where the user is supposed to key in some info. If the user keys in the correct info for something_A, the program should move on to asking user to key in info for something_B.
If the user enters incorrect info for this, the program should throw the respective exception which is InvalidExcep_B. I can get all this to work except once the exception is thrown, the program prompts the user to key in info from the beginning.
What should I do in order for the program to keep prompting only to input the piece of info that was incorrect?
boolean continueInput = true;
userInput = new Scanner (System.in);
System.out.println();
do {
try {
System.out.print("Enter Something_A: ");
something_A = userInput.nextInt();
if (condition ok) {
run statements;
}
System.out.print("Enter Something_B: ");
something_B = userInput.nextInt();
if (condition ok) {
run statements;
}
System.out.print("Enter Something_C: ");
something_C = userInput.nextInt();
if (condition ok) {
run statements;
}
continueInput = false;
}
catch (InvalidExcep_A e) {
System.out.println(e.toString());
continueInput = true;
}
catch (InvalidExcep_B e) {
System.out.println(e.toString());
continueInput = true;
}
catch (InvalidExcep_C e) {
System.out.println(e.toString());
continueInput = true;
}
} while (continueInput == true);
System.out.print("Enter Something_D: ");
something_D = userInput.next();
printInfo (parameters);
}
This is what I have so far. Thank you!

A couple things you could try.
Separating the do-while per input (right now, you have it all in one do-while). A bit repetitive but hey, it gets the job done.
Store a list of [input, actions] and just iterate through that in your while loop, the stop condition being once you finish that list.

You code is almost correct except since we need to remember whether Something_A is already finished or not. Similarly, for Something_B and Something_C we have to remember whether it is finished or not. So, the condition for Something_A, Something_B and Something_C should be different. Hence I chose conditionA, conditionB and conditionC for Something_A, Something_B and Something_C respectively.
The following code should solve your problem:
boolean continueInput = true;
boolean conditionA = true, conditionB = true, conditionC = true;
Scanner userInput = new Scanner (System.in);
System.out.println();
int somethingA = -1, somethingB = -1, somethingC = -1;
String somethingD = "";
do {
try {
if (conditionA) {
System.out.print("Enter Something_A: ");
somethingA = userInput.nextInt();
// runStatementsA();
conditionA = false; // Will not prompt for Something_A again.
}
if (conditionB) {
System.out.print("Enter Something_B: ");
somethingB = userInput.nextInt();
// runStatementsB();
conditionB = false; // Will not prompt for Something_B again.
}
if (conditionC) {
System.out.print("Enter Something_C: ");
somethingC = userInput.nextInt();
// runStatementsX();
conditionC = false; // Will not prompt for SOmething_C again.
}
continueInput = false;
} catch (java.util.InputMismatchException e) { // Replace 'java.util.InputMismatchException' with 'InvalidExcep_A'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
} catch (java.lang.NullPointerException e) { // Replace 'java.lang.NullPointerException' with 'InvalidExcep_B'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
} catch (java.lang.RuntimeException e) { // Replace 'java.lang.RuntimeException' with 'InvalidExcep_C'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
}
} while (continueInput == true);
System.out.print("Enter Something_D: ");
somethingD = userInput.next();
//printInfo(parameters);

Related

Validating input with try-catch

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;}

Do-while loop not waiting for user input?

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);

How to make a try block within a loop?

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;
}

Try not getting executed more than once in while(true) loop

I am writing a simple part of a program where the user gives the year being born. The code is as follows:
while(true){
try {
year = input.nextInt();
break;
} catch (InputMismatchException mismatchException) {
System.err.println("year of birth can only have numbers");
}
}
So what happens is if i give a valid int (year is of type int) everything is ok. If i give a string like "hello" what i expected it to do is to get again inside try and ask me for a number after it has written the error message.
Is my way of thinking wrong concerning try - catch statement?
Try this ( I guess input is java.util.Scanner):
while(input.hasNext()) {
if (input.hasNextInt()) {
year = input.nextInt();
break;
} else {
System.out.println("year of birth can only have numbers");
input.next();
}
}
input.close();
You have to try this so you can get the next input, if you dont give a number:
Scanner input = new Scanner(System.in);
int year;
boolean repeat = true;
while(repeat){
try {
repeat = false;
year = input.nextInt();
} catch (InputMismatchException mismatchException) {
System.err.println("year of birth can only have numbers");
input.next();
repeat = true;
}
}
System.out.println("DONE");

How do I gracefully make a java.util.Scanner wait for input again?

I have the following part of a program, which emulates a very basic menu.
while (true) {
int selection;
try {
selection = scanner.nextInt();
} catch (Exception e) {
selection = -1;
}
switch (selection) {
case 0:
System.exit(0);
default:
System.out.println("No valid selection!");
}
}
Now, whenever I enter not an integer, the selection is set to -1 and the error message is printed. However, the loop continues endlessly, with the Scanner not waiting for any input.
How do I tell it to wait again? How do I fail more gracefully on malformed user input here?
When a Scanner fails to read something, the offending data is not removed from the stream, which means any subsequent read will fail again until the data is cleared.
To fix this, you could, on failure, just read something and ignore the result:
try {
selection = scanner.nextInt();
} catch (Exception e) {
selection = -1;
scanner.next(); // discard the input
}
Not sure throwing and catching an exception is relevant in your case.
Try:
boolean isValid = false;
int selection;
while(!isValid) {
isValid = scanner.hasNextInt();
if(!isValid) {
System.out.println("No valid selection!");
scanner.next();
} else {
selection = scanner.nextInt();
}
}
if(selection == 0) {
System.exit(0);
}
Make some user input exit out/break the while loop. Like if a user enters "Exit" while loop stops.
Besides that you can do something like:
catch (Exception e) {
selection = -1;
}
switch (selection) {
case 0:
System.exit(0);
default:
System.out.println("No valid selection!");
System.out.println("Try again!");
selection = scanner.nextInt();
}

Categories