I need a java program that ask a number between 0 and 2. If the user write 0, the program ends. If the user write 1, it executes one function. If the user write 2, it executes another function. I also want to handle the error "java.lang.NumberFormatException", with a message and in this case, ask again the user for a number, until he writes a number between 0 and 2
I use
public static void main(String[] args) throws IOException {
int number = 0;
boolean numberCorrect = false;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
number = Integer.parseInt(option);
try {
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
case "1":
System.out.println("You choose "+option);
functionA();
numberCorrect = true;
break;
case "2":
System.out.println("You choose "+option);
functionB();
numberCorrect = true;
break;
default:
System.out.println("Incorrect option");
System.out.println("Try with a correct number");
numberCorrect = false;
}
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
}
}
}
But with this code the catch(NumberFormatException z) doesn't work and the program don't ask again for a number.
You never actually catch NumberFormatException here. Your code basically does:
while (...) {
// this can throw NumberFormatException
Integer.parseInt(...)
try {
// the code in here cannot
} catch (NumberFormatException e) {
// therefore this is never reached
}
}
What you want to do here is:
while (!numberCorrect) {
line = br.readLine();
try {
number = Integer.parseInt(line);
} catch (NumberFormatException ignored) {
continue;
}
// etc
}
You could put the try/catch around the parseInt like this:
while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
try {
number = Integer.parseInt(option);
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
option = "-1";
}
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
...
Related
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;}
I have a menu below and I want the menu to repeat when a String is enter instead of a interger.I know when a String is enter into "in/nextInt();" it crashes right away. I was wondering what I can do to stop that from where I am at right now.
Scanner in = new Scanner(System.in);
do{
System.out.println("");
System.out.println("Please choose from the following options. " );
System.out.println("");
System.out.println("1. Do you want to use the default rotor settings? ");
System.out.println("2. Do you want to use the custom rotor settings? ");
System.out.println("3. Start over. ");
System.out.println("");
menuOneAnwser = in.nextInt();
}while(menuOneAnwser < 0 || menuOneAnwser > 3);
try{
switch(menuOneAnwser){
case 1:
Enigma.defaultSwitch = true;
break;
case 2:
Enigma.defaultSwitch = false;
g.customRotor();
break;
case 3:
introduction();
break;
default:
break;
}
}catch(InputMismatchException e){
System.out.println("That is not a integer.... Please enter a interger between 1 and 2!" );
System.out.println("Please try again.." );
System.out.println("");
}
instead of callin scanned.nextInt directly, try to convert that string into an integer catching the exception menas the input is not valid and then set the
menuOneAnwser to -1
do{
System.out.println("");
System.out.println("Please choose from the following options. " );
System.out.println("");
System.out.println("1. Do you want to use the default rotor settings? ");
System.out.println("2. Do you want to use the custom rotor settings? ");
System.out.println("3. Start over. ");
System.out.println("");
try {
menuOneAnwser = Integer.parseInt(input);
} catch (NumberFormatException e) {
menuOneAnwser = -1;
}
}while(menuOneAnwser < 0 || menuOneAnwser > 3);
You can write your own version of tryParse (from C# Int32.TryParse) which will attempt to parse the input as an integer, but will alert you if it isn't (return null in this case), and then you can handle it as a String or whatever you would like:
public static Integer tryParseInteger(String input) {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
return null;
}
}
Try and catch approach:
menuOneAnwser = -1;
while (menuOneAnwser < 0 || menuOneAnwser > 3) {
try {
menuOneAnwser = in.nextInt();
} catch (Exception e) {
System.out.println("Please try again.." );
}
}
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 tried making a menu system to make a user select between four options. To distinguish between the selections I check the int entered. It works but somehow I feel it is not very elegant. Especially when I set the initial value of selectedMenu to 1902475424 to check for when the user entered a mismatcing value. I assumed the user wont accidentally type 1902475424.
Is there a way more simple way to make a menu system or will this do? Is this major flawed?
Yes im a beginner to Java :-)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println(
"1. Start new game\n" +
"2. Load game\n" +
"3. Settings\n" +
"4. Exit\n"
);
}
public void selectMenu() throws InputMismatchException {
int selectedMenu = 1902475424;
Scanner aScanner = new Scanner(System.in);
do {
selectedMenu = 1902475424;
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out
.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
}
if ((selectedMenu < 1 || selectedMenu > 4)
&& (selectedMenu != 1902475424)) {
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
}
} while (selectedMenu == 1902475424
|| (selectedMenu < 1 || selectedMenu > 4));
if (selectedMenu >= 1 && selectedMenu <= 4) {
System.out.println("A new game will now start.");
}
}
}
Your method is leaning into the overkill category :]You can do away with your random value of 1902475424 like so:
public void selectMenu() throws InputMismatchException {
int selectedMenu;
Scanner aScanner = new Scanner(System.in);
do {
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
if(selectedMenu < 1 || selectedMenu > 4) {
System.out.println("Input out of range \"" + selectedMenu + "\". Input..");
}
} catch(InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
selectedMenu = 0;
}
} while(selectedMenu < 1 || selectedMenu > 4);
System.out.println("A new game will now start.");
}
Consider the following alternative (pseudocode):
int getMenuOption() {
print(message)
read(input)
if input is valid then return input
else then return getMenuOption()
}
This is recursive, so if the user sits there and enters bad numbers long enough, you could overflow the stack. You could easily augment this to give the user a fixed number of tries:
int getMenuOption(int triesRemaining) {
if (triesRemaining == 0) throw new RetriesExceededException();
print(message)
read(input)
if input is valid then return input
else then return getMenuOption(triesRemaining - 1)
}
Try something like that (I haven't tested it)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println("1. Start new game\n" + "2. Load game\n"
+ "3. Settings\n" + "4. Exit\n");
}
public void selectMenu() throws InputMismatchException {
int selectedMenu;
boolean validSelection = false;
Scanner aScanner = new Scanner(System.in);
while(!validSelection) {
selectedMenu = aScanner.nextInt();
validSelection = true;
switch (selectedMenu) {
case 1:
// doWhen1();
break;
case 2:
// doWhen2();
break;
case 3:
// doWhen3();
break;
case 4:
// doWhen4();
break;
default:
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
validSelection = false;
}
}
}
}
Here is a revision to the selectMenu() method you provided that should get the job done! I tested it out and it seems to work as expected. :)
public void selectMenu() {
int selectedMenuItem = 0;
Scanner aScanner = new Scanner(System.in);
while(selectedMenuItem == 0){
String userInputMenuItemString = aScanner.nextLine();
try {
int userInputMenuItem = Integer.parseInt(userInputMenuItemString);
if(userInputMenuItem > 0 && userInputMenuItem <= 4){
selectedMenuItem = userInputMenuItem;
}else{
System.out.println("No option #" + Integer.toString(userInputMenuItem) + " exists!\nTry again:");
}
} catch(NumberFormatException ex) {
System.out.println("Please input a number!");
}
}
switch(selectedMenuItem){
case 1:
System.out.println("You chose to start a new game!");
break;
case 2:
System.out.println("You chose to load a game!");
break;
case 3:
System.out.println("You chose to access settings!");
break;
case 4:
System.out.println("You chose to exit. Bye!");
System.exit(0);
break;
}
}
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();
}