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!!");
Related
I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Getting the multiplication table of any number");
while (true) {
try {
System.out.println();
System.out.print("Enter a number: ");
long number = scanner.nextLong();
for (byte num = 1; num < 11; num++) {
System.out.println(number + "X" + num + " = " + (number * num));
}
System.out.println();
System.out.println();
} catch (Exception e) {
System.out.println("Please enter a valid input.");
}
}
}
}
When I run the programm, it run fine till I introduce just one error. Then it just gives the output:
Enter a number: Please enter a valid input.
Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?
You can change your catch block as:
catch (Exception e) {
System.out.println("Please enter a valid input.");
scanner.next();
}
I am trying to implement a (re)try-catch block.
Scanner sc = new Scanner(System.in);
while (true){
try {
t = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("Please enter a whole number without any symbol(s)!");
}
}
But the problem here is that the control again goes into the catch block ones it reaches there and never attempts to execute the try block before that.
Here's how I solved it...
/*java.util.*/Scanner sc = new /*java.util.*/Scanner(System.in);
while(true)
{
if(sc.hasNextInt()){ t=sc.nextInt(); break;}
System.out.println("Please enter a whole number integer (between -2,147,483,649 and 2,147,483,648) without any symbol(s)!");
sc.nextLine(); // hasNextInt() only scans the current line in the buffer
}
I want to ask the user to enter a String, and four integer values, and i want the program to keep asking the user for integer value if the user input a type mismatch, why the code keep looping forever and never wait for the user input if the user inserted a wrong type ?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
According to scanner oracle docs :
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
So when you entered anything other than an integer, the scanner.nextInt() will not parse it to integer and throw InputMismatchException and the scanner will not move to the next token and tried to read again and again the same token.
To solve this, you can either change the loop or use hasNextInt() method or use scanner.next() in the catch block so that the scanner can move to the next token.
I always use do-while loop when checking for correct Input from the user.
See if the following works:
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv = -1, breakInterv = -1, terminalBreakInterv = -1;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
boolean isPomoInterv = false;
do {
System.out.println("Please, Enter the Pomodoro interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
pomoInterv = Integer.parseInt(temp);
isPomoInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isPomoInterv);
boolean isBreakInterv = false;
do {
System.out.println("Please, Enter the break interval: ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
breakInterv = Integer.parseInt(temp);
isBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isBreakInterv);
boolean isTerminalBreakInterv = false;
do {
System.out.println("Please, Enter the terminal break interval ");
String temp = scanner.nextLine();
try {
if (Integer.parseInt(temp) > 0) {
terminalBreakInterv = Integer.parseInt(temp);
isTerminalBreakInterv = true;
}
} catch (NumberFormatException e) {
System.out.println("Try again");
}
} while (!isTerminalBreakInterv);
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
The comment on your question by scary-wombat is correct. i have used his comment to code the above.
I actually solved it, i just had to add a (scanner.next();) in the catch statement as below, it's because how the Scanner class works, see the code below,
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sessionName;
int pomoInterv, breakInterv, terminalBreakInterv;
System.out.println("Please, Enter the session name: ");
sessionName = scanner.nextLine();
while (true) {
try {
System.out.println("Please, Enter the Pomodoro interval: ");
pomoInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true) {
try {
System.out.println("Please, Enter the break interval: ");
breakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
while (true){
try {
System.out.println("Please, Enter the terminal break interval ");
terminalBreakInterv = scanner.nextInt();
break;
} catch (InputMismatchException ex) {
scanner.next();
System.out.println(ex.getMessage());
}
}
System.out.println("Done!");
System.out.println(sessionName);
System.out.println(pomoInterv);
System.out.println(breakInterv);
System.out.println(terminalBreakInterv);
}
}
check this answer
https://stackoverflow.com/a/47852703/12565862
Because you don't have a break; in catch block. When there is exception, you print the message. But once it comes out of catch block, while loop still satisfies its condition and execute again. Try adding break; inside catch block too.
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! ";
}
I would like the program to re-do the while loop when it catches the exception - the exception being receiving a number zero. Instead it continues a while loop with the code below, I would like it to ask for the user input again until the user inputs a number that is different by zero.
import java.util.InputMismatchException;
import java.util.Scanner;
public class whilePerjashtim {
public static int division(int a, int b){
return a/b;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a, b;
System.out.println("Enter a value: ");
a = s.nextInt();
while(true){
try
{
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of division is: " + division(a,b));
}
catch(ArithmeticException e)
{
System.err.println("Don't divide by zero!!!");
}
catch (java.util.InputMismatchException e)
{
System.err.println("Enter just a Number!!!");
}
finally
{
System.out.println();
}
}
}
}
Use something of the following form (not exact Java for your homework problem)
boolean validInput = false;
while (!validInput) {
.. get input
.. set validInput = true if no error
.. catch error
.. print try again message
}
You can set a boolean value, that determines, if the while loop ends succesfully. Then in every loop you start by assuming the value is true and when an exception is raised, you set it to false.
boolean success = false;
while(success == false){
success = true;
try {
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of divison is: " + division(a,b));
}
catch(ArithmeticException e) {
System.err.println("Dont divide by zero!!!");
success = false;
}
}
Define a boolean outside of your while loop, and use it for the while's condition.
Assuming I understood your question correctly, you want to stay in the loop if the user's input threw an exception, ie it was invalid input, and you want to break out of the loop when you get valid input from the user.
boolean gotValidInput = false;
while (!gotValidInput) {
try {
System.out.println("Enter b value");
b = s.nextInt();
gotValidInput = true;
System.out.println("Sum of divison is: " + division(a,b));
} catch(ArithmeticException e) {
System.err.println("Dont divide by zero!!!");
} catch (java.util.InputMismatchException e) {
System.err.println("Enter just a Number!!!");
} finally {
System.out.println();
}
}
In this implementation, your two exceptions would both be thrown before gotValidInput = true; gets evaluated, so it would only get set to true if no exceptions were thrown.
You can put extra outter loop, like
while (true) {
System.out.println("Enter a value: ");
a = s.nextInt();
while(true) {
/// terminate the loop in case of problem with a, and allow a user to re done
}
}
Cleaned up the warnings and moved s to ouside the main method and defined it as static. It appears the s is a resource leak if within the main and is never closed.
import java.util.InputMismatchException;
import java.util.Scanner;
public class whilePerjashtim {
private static Scanner s;
public static int division(int a, int b) {
return a / b;
}
public static void main(String[] args) {
int a, b;
s = new Scanner(System.in);
System.out.println("Enter a value: ");
a = s.nextInt();
boolean input = false;
while (input == false) {
try {
System.out.println("Enter b value");
b = s.nextInt();
System.out.println("Sum of division is: " + division(a, b));
input = true;
}
catch (ArithmeticException e) {
System.err.println("Don't divide by zero!!!");
}
catch (InputMismatchException e) {
System.err.println("Enter just a Number!!!");
}
finally {
System.out.println();
}
}
}
}
You need to handle the erroneous input as well if you want the while loop to continue properly: You need to get rid of the erroneous input at the end of each catch block. Adding continue will simply make the loop run again until the user gives the correct input.
catch (InputMismatchException e)
{
System.err.println("Enter just a Number!!!");
//add this
s.nextLine();
continue;
}