Try and Catch with JOption Does not work as expected - java

int i=0;
int c=0;
int a=0;
int b=0;
String stringy;
String input;
do { //loop for value a
try // try-catch to prevent program from crashing
{
stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit:");
if (stringy.equalsIgnoreCase("q")) System.exit(0);
a = Integer.parseInt(stringy);
i++;
} catch (Exception e) {
stringy= JOptionPane.showInputDialog("Error. Try Again! ");
} // end catch
} while(i==0); // end loop
the output produces a jOption input dialog box ("type a value...") and when i enter in a string or something that the system does not expect, it goes to the "catch"and pops out "error try again!" However, when i enter in anything into that, even if it is a number, it goes back to the ("type a value...") dialog box. I want it to read the input in the error box instead of jumping back to the first dialog box. Thank you for your help!

You should take base input out of cycle, if you want to use input from catch().
And use break; clause unstead of while(i==0) and i++;
stringy= JOptionPane.showInputDialog("Type a value for a or press q to quit: ");
while(true)
{
if (stringy.equalsIgnoreCase("q")) System.exit(0);
try {
a = Integer.parseInt(stringy);
break;
} catch (Exception e) {
stringy= JOptionPane.showInputDialog("Error. Try Again! ");
}
}
JoptionPane.showMessageDialog("Input accepted!");
And write your code in correct format please, you have commented '{' at the start of cycle.

You obviously have to check the input of the second dialog too, similar to the following:
stringy = JOptionPane.showInputDialog("Error. Try Again! ");
if (stringy.equalsIgnoreCase("q")) {
System.exit(0);
}

How about adding a String for output.
String input;
String output = "Type a value for a or press q to quit: "
do //loop for value a {
try // try-catch to prevent program from crashing
{
stringy= JOptionPane.showInputDialog(output);
if (stringy.equalsIgnoreCase("q"))
{
System.exit(0);
}
a= Integer.parseInt(stringy);
i++;
}
catch (Exception e)
{
output= "Error. Try Again! ";
}

Related

logical error while Checking Whether the input was numeric, if not re-request users input until valid

when an invalid input is entered it goes to the catch block and infinitely executes the catch block without looping back to try block to get another input
It works when valid data is entered
public static double getInputNumber(Scanner input){
double num=0;
while(true) {
try {
num = input.nextDouble();
return num;
} catch (Exception ex) {
System.out.println("Invalid value entered.. Enter again : ");
}
}
}
expected - when an invalid value entered,show the user the error message and get a re-input until the users enters a valid value.
actual - when invalid value entered it displays the error message repeatedly in the screen without going for a re-input
It could well be that input has been closed, or the next token in the input is NOT a double. Either of these would cause an exception to be thrown, without advancing the input, so resulting in your infinite loop.
So you need to catch the cause of the error, to take the appropriate action - eg, something like :
public static double getInputNumber(Scanner input){
double num=0;
while(true) {
try {
num = input.nextDouble();
return num;
} catch (InputMismatchException ex) {
System.out.println("Invalid value entered.. Enter again : ");
} catch (NoSuchElementException ex) {
System.out.println("Input exhausted ");
return 0;
} catch (IllegalStateException ex) {
System.out.println("Scanner closed ");
return 0;
}
}
}
}
You could also use input.hasNextDouble() to check before calling nextDouble()
Just add input.next()
} catch (Exception ex) {
System.out.println("Invalid value entered.. Enter again : ");
input.next();
}
input.next() clears scanner.

Write a program that will give the use prompt to enter two doubles value

Professor requires us to write a program that will give the user prompt to enter two float (or double) values. If the values inputted are correct then display the inputted two values. If user enters characters instead of numbers or if they enter invalid numbers then the program will display the error message and ask the user to re-enter the correct values again. It only exits when the correct input is received and displayed.
However, I wrote a program that will only work if the user input the two right doubles. Can someone helps me to change the line about catching errors? Thanks.
import java.util.Scanner;
public class FiveSecond {
static void printMenu() {
System.out.println("Welcome to get two doubles program:");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean valid = false;
double first = 0;
double second = 0;
printMenu();
while(!valid) {
System.out.print("Enter two doubles, seperate by space ");
try {
first = Double.parseDouble(scan.next());
second = Double.parseDouble(scan.next());
} catch (NumberFormatException e) {
System.out.println("Try again");
}
valid = true;
}
System.out.println("You entered valid choice: " + first + " " +second);
System.out.println("Thank you for giving your choice.");
scan.close();
}
}
Try this:
catch (NumberFormatException e) {
System.out.println("Try again");
continue;
}
In addition to the previous comments, you have to be careful, because the scanner will 'remember' a previously correct double if you don't reset it :
EDITED: Thanks to #Stultuske comment
while (!valid) {
System.out.print("Enter two doubles, seperate by space ");
try {
first = Double.parseDouble(scan.next());
second = Double.parseDouble(scan.next());
valid = true;
}
catch (NumberFormatException e) {
System.out.println("Try again");
scan.nextLine(); // <------- Important line
}
}

Java try catch (InputMismatchException) unexpected loop

Im trying to catch an InputMismatchException it works at the first interraction , but when the menu() method is called again , it starts looping until it gets stuck in an error.
In the try catch my objective was to get an error message and after that start the menu() method again.
I have the following code:
public class Menu extends ProfilesManager {
static Scanner sc = new Scanner(System.in);
public static void menu() {
int number;
System.out.println("** Welcome... **\n ");
System.out.println("* what you wanna do?:\n");
System.out.println("(1) Login \n(2) Register \n(3) Find User \n(4) Exit\n");
System.out.print("-Answer?: ");
try {
number = sc.nextInt();
if (number == 1) {
Login();
} else if (number == 2) {
Register();
} else if (number == 3) {
FindUser();
} else if (number== 4) {
Exit();
}
} catch (InputMismatchException e) {
System.out.println("Error , only numbers!!");
menu();
}
}
}
}
This is because once you enter a wrong input. you are not clearing it and Scanner will keep on reading it and every time it will give you InputMisMatchException
You need to clear it in your catch block
}catch(InputMismatchException e){
System.out.println("Error , only numbers!!");
sc.nextLine();
// Put 2 second delay
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
ex.printStackTrace();
}
menu();
}
You have infinite recursion. You gotta move menu() out of the catch block if you want to call it again. Otherwise it's infinite loop.
I guess you should write sc = new Scanner(System.in); after System.out.println("Error , only numbers!!");

Java - try/catch infinite repeat

Requirement:
Accept 10 numbers, input them into an array and then invoke a method to calculate and return the smallest. This program is suppose to be error proof so when a user enters an invalid entry, it notifies the user and reprompts. I am trying to use try catch but when an invalid entry is entered, ie a character, the scanner won't reprompt.
Any ideas?
Tried:
//Variables
double [] doubleArray = new double[10];
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("This program will prompt for 10 numbers and display the smallest of the group");
//Get values
for (int i = 0; i < doubleArray.length; i++) {
try {
System.out.println("Please enter entry "+ (i+1));
doubleArray[i] = input.nextDouble();
} catch (InputMismatchException e) {
// TODO: handle exception
System.out.println("Please enter a rational number");
i--;
}
}
//Invoke method and display result
System.out.println("The smallest value is: "+index(doubleArray));
I don't see any call to input.nextLine(), which means nothing is ever consuming the \n entered by the user. There's a good example on scanner.nextLine usage here. If you add a call to it in your catch block, you should be all set.
Try calling input.nextLine(); in your catch. Then the \n will be taken from the input which let's you enter the next new number.
for(int i = 0; i < doubleArray.length; ++i) {
try {
doubleArray[i] = input.nextDouble();
} catch(Exception e) {
input.nextLine();
--i;
}
}
Try something like (and make sure you consume the whole line unless you want to allow multiple numbers to be input on the same line
boolean validEntry = false;
System.out.println("Enter a rational number: ");
while (!validEnry) {
try {
double value = input.nextDouble();
validEntry = true;
doubleArray[i] = value;
} catch (Exception e) {
System.out.println("Entry invalid, please enter a rational number");
}
}
...
You have to discard the false inputted data, add input.nextLine() in the catch block.

Scanner keeps skipping input whist using nextInt() and loops

I am using a while loop to make sure that the value entered to a scanner object is an integer as such:
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
}
}
however, if the user does not enter an integer, when it should go back and take another input it just repeatedly prints "Capacity" followed by the output in the catch without asking for more input. How do I stop this?
scan.nextLine();
Put this piece of code inside your catch block, to consume the non integer character along with the new line character which is stays in the buffer(hence, infinitely printing the catch sysout), in the case where you've given a wrong input.
Ofcourse, there are other cleaner ways to achieve what you want, but I guess that will require some refactoring in your code.
Use the following:
while (!capacityCheck) {
System.out.println("Capacity");
String input = scan.nextLine();
try {
capacity = Integer.parseInt(input );
capacityCheck = true;
} catch (NumberFormatException e) {
System.out.println("Capacity must be an integer");
}
}
Try this :
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
scan.nextLine();
}
}
Try putting this at the end of the loop -
scan.nextLine();
Or better to put it in the catch block.
while (!capacityCheck) {
try {
System.out.println("Capacity");
capacity = scan.nextInt();
capacityCheck = true;
} catch (InputMismatchException e) {
System.out.println("Capacity must be an integer");
scan.nextLine();
}
}
I see no need for a try/catch or capacityCheck as we have access to the method hasNextInt() - which checks if the next token is an int. For instance this should do what you want:
while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token.
System.out.println("Capacity must be an integer");
scan.next();
}
capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.

Categories

Resources