I'm trying to create simple Menu for my program. I use InputMismatchException to catch exception when user enter char instead of integer but the program is looping when I enter char.
I left callMenu method empty but I'll fill it after solving this problem.
I am not sure is the mistake in the main menu or in catch part. When I do not write kb.nextInt() in catch section I'm getting infinitive loop. In another case it displayes mistake
public static void main(String[] args) {
do {
Menu.showMenu();
Menu.callMenu(Menu.getChoice());
} while (true);
}
}
import java.util.Scanner;
import java.util.Scanner.*;
import java.util.InputMismatchException;
public class Menu {
public static void showMenu() {
System.out.println("----------Menu----------");
System.out.println("1 - ");
System.out.println("2 - ");
System.out.println("0 - Exit");
}
public static int getChoice() {
Scanner kb = new Scanner(System.in);
System.out.print("\n Enter menu number:");
int choice = kb.nextInt();
while (!isValidChoice(choice)) {
try {
System.out.println("\n INVALID INPUT. Try again.");
System.out.print("Enter menu number: ");
choice = kb.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error");
kb.next();
}
}
return choice;
}
public static boolean isValidChoice(int ch) {
return ch >= 0 && ch <= 9;
}
public static void callMenu(int menuNum) {
switch (menuNum) {
case 1:
break;
case 2:
break;
case 0:
System.exit(0);
}
}
}
I am not going to modify your code a lot. Here is what i can see wrong and what i think you can change
The point that your are getting the first input will throw an exception if you do not enter a integer. You do not have a catch block around it. So you should take that inside the try catch block to capture any invalid inputs
The main method will keep running infinitely when you check the value as "true" in while condition. Change that to false.
What i am providing you below assumes that your program will exit if an character/Non-Integer value in entered by displaying an error message.If the inputs are integers, your code will loop until one of your correct menu items are reached
I am only putting in the changes and not the whole code below. Rest remains same.
public static int getChoice() {
Scanner kb = new Scanner(System.in);
System.out.print("\n Enter menu number:");
int choice=-1;
try{
choice = kb.nextInt();
while (!isValidChoice(choice)) {
System.out.println("\n INVALID INPUT. Try again.");
System.out.print("Enter menu number: ");
choice = kb.nextInt();
}
}catch (InputMismatchException e) {
System.out.println("Error");
}
return choice;
}
In your main method
public static void main(String[] args) {
do {
Menu.showMenu();
Menu.callMenu(Menu.getChoice());
} while (false);
}
Hope this works out. Let me know
Related
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.
I am new in java. I have written a program in which the user chooses how many numbers he wants to add. If the user enters a string it will throw an exception and the programs tell the user to enter all details again.
My problem is i want the program to ask the user to re enter details from that number which he entered wrong.
Eg: the user chooses to add 4 numbers but he enters the third number as string, the program should ask the user to re-enter from the third number and not the entire details again.
My code is as follow:
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;
while(loop)
try
{
String yn;
do
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
System.out.println("Try Again\n");
}
}
}
You can resolve this, by placing the "retry" one level deeper in the code:
import java.io.*;
import java.util.*;
class Add {
public static void main(String args[]) throws Exception {
boolean loop=true;
Scanner s=new Scanner(System.in);
while(loop) {
try {
String yn;
do {
loop = true;
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;) {
try {
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}
catch(Exception e) {
System.out.println("Invalid input. Try Again.\n");
}
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
loop = yn.equals("y")||yn.equals("Y");
} while(loop);
}
catch(Exception e) {
System.out.println("Number of elements invalid. Try Again.\n");
}
}
}
}
As #Zhuinden indicates, one better uses Scanner.nextInt, since it is more generic...
Below code should help
int i =1;
while(i <=num){
System.out.println("Enter number["+i+"]: ");
try{
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}catch(NumberFormatException ex){
System.out.println("Please enter a valid interger");
}
}
Use additional method that reads single entry until it is valid number:
private static int readNumber(Scanner s) {
Integer value = null;
while (value == null) {
try {
value = Integer.parseInt(s.next());
} catch (NumberFormatException e) {
System.out.println("bad format, try again...");
}
}
return value;
}
Then you can use this method whenever you can read valid number:
System.out.println("Enter how many numbers to add: ");
int num = readNumber(s);
...
System.out.println("Enter number[" + i + "]: ");
a = readNumber(s);
....
Method getNumber(s) guarantee to return only when user give correct integer.
works according to what you want, but not ethical
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;int pos=0;int num=0,sum=0;
while(loop)
try
{
String yn;
do
{sum=0;num=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
num=Integer.parseInt(s.next());
int a;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;pos=i;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
Scanner s=new Scanner(System.in);
int a=0;
for(int i=pos+1;i<=num;i++)
{ System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;}
System.out.println("The Sum is:"+sum);
}
}
}
So, I've searched around google and stackoverflow for a bit, but I can't seem to find an answer to this issue.
I've got 2 methods. The first method, getAge is meant to just get an integer as input from the user. It's then meant to pass that input to verifyAge, who makes sure it's in the right range.
However; if they should enter anything that is not an integer, it's supposed to display a message and call getAge again, to restart the input process. I have a try-catch set up, but it still goes back to JVM. According to an answer in another post; what I'm doing is correct. But it still doesn't seem to be working. So here's the errors I get when I try to run it as I have it now:
Please enter your age: notint
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Ch2ProgLabWilson.getAge(Ch2ProgLabWilson.java:22)
at Ch2ProgLabWilson.main(Ch2ProgLabWilson.java:15)
What I have written:
import java.util.* ;
import java.util.Scanner;
public class Ch2ProgLabWilson {
public static void main(String[] args) {
getAge();
}
public static int getAge()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
getAge();
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}
return a;
}
//
public static boolean verifyAge (int a)
{
if (a >= 0 && a <= 122)
{
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}
else
{
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
getAge();
return false;
}
}
}
The Exception is being thrown by int a = keyboard.nextInt();, which is outside of the try catch block.
Place the call to int a = keyboard.nextInt(); inside the try block.
There are other problems with your code:
verifyAge() returns a boolean that is never used.
Your getAge() method is recursive and, assuming that the user enters a number, it will just loop - is this what you intended?
UPDATE
public static int getAge(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = -1;
while(!verifyAge(age)){ // will loop until there's a valid age
try{
age = scanner.nextInt();
catch (InputMismatchException e){
System.out.println("You may only enter integers as an age. Try again.");
}
}
return age; // your current code doesn't do anything with this return value
}
public static boolean verifyAge (int a){ // would be better named isValidAge()
if (a >= 0 && a <= 122){
System.out.println("The age you entered, " + a + ", is valid.");
return true;
}else{ // no need to call getAge() here
System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
return false;
}
}
well the code is not within the try block
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int a = keyboard.nextInt();
verifyAge(a);
try
{
so it will not get caught.
Look at the line of code which actually throws the Exception. If it is not in the try/catch block, it will not be caught.
Try this instead:
try
{
int a = keyboard.nextInt();
verifyAge(a);
}
catch (InputMismatchException e)
{
System.out.println("You may only enter integers as an age. Try again.");
getAge();
}
If I enter the wrong input(example , if I enter String instead of Integer) loop is not ending, it wont get input next time. Here(below) i attach the entire program. can you please help this?. Thanks in advance!!!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
*
* #author Nithish
*
*/
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
e.printStackTrace();
}
}
}
}
On an InputMismatchException you are doing i--, so the loop condition is modified to prevent the loop from ending without the needed input. If you read the API documentation for Scanner.nextInt() you should notice the following:
If the translation is successful, the scanner advances past the input that matched.
This means that if the input cannot be translated to int, the scanner does not advance. So on the next invocation of nextInt() it will re-read the exact same, non-int, input and fail again. You will need to read past that non-integer token before attempting to get an int again.
Again, don't mess with the loop index inside of the loop as this can cause problems down the road. Instead use a while loop which is much cleaner and much easier to debug 3 months from now:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean done = false;
int result = 0;
while (!done) {
try {
System.out.print("Enter the value: ");
String temp = scanner.nextLine();
result = Integer.parseInt(temp);
done = true;
} catch (NumberFormatException e) {
System.out.println("Please only enter integer data");
}
}
scanner.close();
}
}
what about the below?
Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
System.out.println("Enter the value");
if (src.hasNextInt()) {
i = src.nextInt();
System.out.println("Thank you! (" + i+ ")");
}
else
{
System.out.println("Please only int");
}
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
try {
System.out.println("Enter the value");
int obj = scanner.nextInt();
System.out.println(obj);
} catch (InputMismatchException e) {
i--;
//e.printStackTrace();
scanner.nextLine(); //you can add this here.
//scanner.next(); you can also use this
}
}
I'm trying to loop an exception, but for some reason its not giving me the option to re write my scanner file:
I don't know how to use BufferedReader so that's why I'm using this. Any clues?
Here's my standard class with my method
package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {
int firstInt;
int secondInt;
boolean error;
Scanner yourNumbers = new Scanner(System.in);
public void findNumbers()
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
}
}
And here's my main class with the exception being implemeted with a loop:
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
GetThoseNumbersBaby zack = new GetThoseNumbersBaby();
{
do {
try
{
zack.findNumbers();
}
catch(InputMismatchException Q)
{
System.out.println(" one of your integers was incorrect, please try again");
Q.printStackTrace();
error = true;
}
} while (error == true);
}
error = false;
}
}
If anyone has any ideas on how to loop this differently I'm all ears.
Set error false before the action. That way you have the correct exit condition if the user gets it right.
error = false;
zack.findNumbers();
i decided too get rid of the method class
and just put the method into the try exception area.
used a .nextLine after scanner and it seems fixed.
this looks ok?
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
do{
try
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
yourNumbers.nextLine();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
yourNumbers.nextLine();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
yourNumbers.nextLine();
}
catch(InputMismatchException Q)
{
Q.printStackTrace();
System.out.println(" one of your integers was incorrect, please try again");
error = true;
yourNumbers.nextLine();
}
}while (error == true);
}error = false;
}
}
You loop while 'error' variable has value 'true'. However, it becomes 'true' only when the is thrown (i.e. when 'catch' block is executed). Control flow doesn't reach it.