I need to check users input. I have a menu and I need the user to select numbers 0-4 but if the user selects a letter instead of a number then I just get a InputMismatchException. So I am trying to validate that the user entered a number. Here is my code:
public class TestBankAccount {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
int choice;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
choice = input.nextInt();
switch (choice) {
case 1:
depositMoney(list);
break;
case 2:
withdrawMoney(list);
break;
case 3:
checkBalance(list);
break;
case 4:
createNewAccount(list);
break;
case 0:
System.out.println("Thank you for trusting us with your banking needs!");
break;
default:
System.out.println("Invalid option is selected!");
}
System.out.println();
} while (choice != 0);
if (list.size() > 0) {
displayResults(list);
}
}
I was thinking to do something like while (choice != 0 && choice != input.hasNextInt()); but I get an error. Any ideas?
You can do somehting like this :
int choice = 0 ;
try{
choice = Integer.parseInt(input.next());
}
catch(NumberFormatException e)
{
System.out.println("invalid value enetered");
}
// Now you can check if option selected is between 1 & 4
// and throw some custom exception
Either catch the exception and handle it, or instead of Scanner use
(char) System.in.read();
to receive characters. In this way you can avoid handling exceptions, which takes a lot of time. You can work on chars instead of integers then or check their validity and convert them to integers in this way:
int x = Character.getNumericValue(choice);
Just wrap it in a try catch
do{
try{
System.out.println(choices)
choice = input.nextInt()
switch(choice){
....
}
}
catch(InputMismatchException){
System.out.println("Please enter a valid input")
}
}
while(whatever)
I found the answer out. This is how I would validate the account number's.
int number;
while(true){
System.out.print("\nEnter account number: ");
try{
number = input.nextInt();
break;
}catch(Exception e){
System.err.println("Error: Invalid Entry! Please try only Integers");
input=new Scanner(System.in);
}
}
and this is how I would validate the menu item selected is a number and not a letter:
int choice = 0;
do {
while(true)
{
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
try{
choice = Integer.parseInt(input.next());
break;
}
catch(Exception e){
System.err.println("Error: Invalid entry! Please Try Again!");
input=new Scanner(System.in);
continue;
}
}
Related
I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.
I'm trying to get a code that gives several options to pick from and while I can get those to work it ends immediately after when I need it to go back to the options.
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}
public static void subtraction(){
Scanner input = new Scanner( System.in );
int number1;
int number2;
int difference;
System.out.print( "Enter First integer: " );
number1 = input.nextInt();
System.out.print( "Enter Second integer: ");
number2 = input.nextInt();
difference = number1 - number2;
System.out.printf( "The difference is %d\n", difference);
}
I've tried several different while loops in an attempt to get it to return to the options but it either endlessly loops or doesn't work.
EDIT: I've added one of the methods to it as an example. the case suggestion doesn't work as I think the format it too different
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice!=5){
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}}
Here's the only while code i can get to run. it infinitely loops itself.
Your best bet to achieve what you are looking to do is to use a Do-While loop. Pay attention to where you ask for the input and then should the choice be equal to your stopping condition, put that as the conditional in the while part of the loop.
While loops will run 0-N times, while Do-While loops always execute 1-N times. Use this to your advantage.
This is a good reference:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
You need to put the things you need to do over and over again, in a loop.
public static void main(String[] args) {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice!=5){
if (choice == 1) {
pythagoraen();
}
else if (choice == 2) {
subtraction();
}
else if (choice == 3) {
multiplication();
}
else if (choice == 4) {
division();
}
System.out.println("What is your next Choice? ");
choice = input.nextInt();
}
}
If you need the print the menu again, then you can put that also inside the loop. What you are doing here, is asking the user for input and then choosing the operation you want to do. Then at the end, you ask the user again about what to do next. If the user enters 5, the while condition becomes false and it exits the loop.
I also removed the if choice == 5 condition because the while loop will handle that scenario. Also added else before each if after the first one. That's for efficiency so that it doesn't check rest of the matches if it is matched with the first one.
There are many ways to achieve this but a better way to do it is with the use of a switch. With switch statements you can have a number of execution paths which seem to fit this situation better then the while loop being used. However, a while loop and a switch statement can not really be compared in terms of efficiency as they are fundamentally different, as can be seen in this article. here is how the implementation would look like with switches:
public static void main(String[] args) {
int exitFlag = 0;
int choice = showMenu();
do {
switch (choice) {
case 1:
System.out.println("pythagoraen()");
break;
case 2:
System.out.println("subtraction()");
break;
case 3:
System.out.println("multiplication()");
break;
case 4:
System.out.println("division()");
break;
case 5:
System.out.println("exitprogam()");
exitFlag = 1;
break;
default:
System.out.println("Invalid Option()");
break;
}
if (exitFlag != 1) {
choice = showMenu();
}
}while (choice != 5);
}
private static int showMenu() {
System.out.println("Hello, This is the math program");
System.out.println("Select an application from below: \n");
System.out.println("(1) pythagoraen");
System.out.println("(2) Subtraction");
System.out.println("(3) Multiplication");
System.out.println("(4) Division");
System.out.println("(5) Exit");
System.out.println("What is your Choice? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
return choice;
}
This is a lot cleaner and easier in the long run for refactoring. For more information on switches please refer to oracle docs.
Try this with the while loop
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
while(choice != 5) {
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice == 1) {
pythagoraen();
System.out.println(pythagoraen());
} if (choice == 2) {
subtraction();
} if (choice == 3) {
multiplication();
} if (choice == 4) {
division();
} if (choice == 5){
exitprogam();
}
}
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.." );
}
}
the following code terminate after try catch block catches exception.its not allowing me to make choice from the menu option. so my question is what changes do i have to make on this code so that i can loop back so that i can get user input again.
public class Main {
public static void main(String[] args) {
Modify modifyObj = new Modify();
int choice = 0 ;
Scanner input = new Scanner(System.in);
//begin loop
do {
try{
//display menu
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
choice = input.nextInt(); //gets user input
switch (choice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}// end of switch statement
break;
}//end oftry
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
continue;
}
}while (choice!=0); //loop until user exit 0.
}//end of main
}// end of Main class
Make sure choice isn't 0 before you continue;
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
choice = 1; // <-- not 0.
continue;
}
Note that you default choice to an initial value of 0.
You Could Use Methods
If you extracted your logic into one (or two) utility methods to display the menu and get the user's choice it would simplify things; something like
private static void showMenu() {
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
}
private static int getUserOption(Scanner input) {
while (true) {
showMenu();
if (input.hasNextInt()) {
int t = input.nextInt();
switch(t) {
case 0: case 1: case 2: case 3:
return t;
}
} else {
input.nextLine();
}
}
}
Then your main could invoke it like
public static void main(String[] args) {
Modify modifyObj = new Modify();
Scanner input = new Scanner(System.in);
int choice;
// begin loop
do {
choice = getUserOption(input);
if (choice != 0) {
System.out.printf("You chose %d.%n", choice);
}
} while (choice != 0); // loop until user enters 0.
}// end of main
I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}
Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)
As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));