Switch Statement not exiting loop. (Java) - java

I have a simple menu system set up where the user hits 8 to leave. However for some reason when i hit 8 during testing it simply goes back to the top of the loop like nothing happened.
package potluck;
import java.util.*;
import potluck.*;
public class Controller {
private Scanner input;
private final static int USER_LOGIN = 0;
private final static int CREATE_MEMBER = 1;
private final static int CREATE_ADMIN = 2;
private final static int CREATE_RECIPE = 3;
private final static int COMMENT = 4;
private final static int DELETE_RECIPE = 5;
private final static int EXIT = 8;
public Controller(){
input = new Scanner(System.in);
startUp();//no better name to be thought of
}
public void startUp() {
// TODO Auto-generated method stub
int choice;
do {
this.displayMenu();
choice = input.nextInt();
input.nextLine();// clears carriage return
//depending on choice takes to a different menu
switch (choice) {
case CREATE_MEMBER:
Member member = new Member();
break;
// case CREATE_ADMIN:
// member.addAdmin();
// break;
case CREATE_RECIPE:
Recipe.addRecipe();
break;
case COMMENT:
Recipe.addComment();
break;
case DELETE_RECIPE:
Recipe.deleteRecipe();
break;
case EXIT:
System.out.println("Thanks for using our software");
break;
default:
System.out.println("Error, Invalid selection.");
}
} while (choice != 8); //choice 8 exits
}
private void displayMenu() {
System.out.println("1 Create Member");
System.out.println("2 Create Admin Member");
System.out.println("3 Create Recipe");
System.out.println("4 Leave Comment");
System.out.println("5 Delete Recipe");
System.out.println("8 Exit");
System.out.println("Please enter menu option, to exit enter 8");
}
}
In testing it claims that choice is 8, which should break the do while...but doesn't...
UPDATE: When copying over code, I left in some work around that i was told not to use. I had system.exit in there under choice 8, but was told that's bad code

Sorry everyone. I'm an idiot. In the main where I launch this, I had instantiated a new controller (which is the class you're looking at) which in the constructor launches the menu. Then i called the startup() method. Which means that it was working perfectly, it was just running twice because i'm dumb.
public static void main(String[] args) {
// TODO Auto-generated method stub
Controller cntlr = new Controller();
cntlr.startUp();
}
public Controller(){
input = new Scanner(System.in);
startUp();//no better name to be thought of
}
public void startUp() {
// TODO Auto-generated method stub
int choice;
do {
this.displayMenu();
choice = input.nextInt();
input.nextLine();// clears carriage return
//depending on choice takes to a different menu
switch (choice) {
case CREATE_MEMBER:
Member member = new Member();
break;
case CREATE_ADMIN:
member.addAdmin();
break;
case CREATE_RECIPE:
Recipe.addRecipe();
break;
case COMMENT:
Recipe.addComment();
break;
case DELETE_RECIPE:
Recipe.deleteRecipe();
break;
case EXIT:
System.out.println("Thanks for using our software");
break;
default:
System.out.println("Error, Invalid selection.");
}
} while (choice != 8); //choice 8 exits
}
private void displayMenu() {
System.out.println("1 Create Member");
System.out.println("2 Create Admin Member");
System.out.println("3 Create Recipe");
System.out.println("4 Leave Comment");
System.out.println("5 Delete Recipe");
System.out.println("8 Exit");
System.out.println("Please enter menu option, to exit enter 8");
}
}
TL;DR. I'm dumb, and constructors are a thing I should pay more attention to.

Related

Java Looping Meters Conversion Program

I cannot figure out how to have the program loop through the Conversion Menu and then return to the Main Menu from choice "4 Return" as shown in the example.
Example of what the program output might look like:
Main Menu
Enter Distance
Quit the program
Please enter your choice: 1
 
Enter a distance in meters: 500
 
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 1
500 meters is 0.5 kilometers
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 3
500 meters is 1640.5 feet
 
Conversion Menu
Convert to kilometers
Convert to inches
Convert to feet
Return
Enter your choice: 4
 
Main Menu
Enter Distance
Quit the program
Please enter your choice: 2
 
Good Bye!
I've found multiple solutions for the program when it doesn't include the main menu and the looping back to it but I can't seem to find anything on this.
Here's what I have:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int choice;
int option;
double meters = 0;
conversionControl();
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
break;
case 2:
quitProgram();
break;
default:
showError("Please Enter a Valid Option");
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
}
do{
menu();
choice = keyboard.nextInt();
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
conversionControl();
option = keyboard.nextInt();
if (option == 1) {
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
}
else if ( option == 2) {
quitProgram();
}
break;
default:
showError("Please Enter a Valid Option");
menu();
choice = keyboard.nextInt();
break;
}
} while(choice != 0); {
}
}
I guess I did figure my own way out but I keep thinking it isn't the correct way or there's an easier way. Plus, some errors occur when testing some inputs (mainly the the showError method calls will output either the incorrect menu or it will just close the program after so many wrong inputs).
Any help/constructive criticism would be greatly appreciated. I'm somewhat new to coding (know HTML) and new to to this site as well.
Thank you!
Bob
As it look like an exercise I won't give you a complete code, but a pseudo code to help you understand the strategy here.
To clarify, I'll name your first menu as mainMenu and the second as convMenu.
You have already implemented the good strategy for the convMenu. The idea is to make a loop, and exist only when the user tells you so. What you are missing is to do the same for the mainMenu and to think the convMenu as a sub-menu of the mainMenu. Which means when you are in the convMenu you are not outside of the mainMenu.
//That's pseudo code
do {
displayMainMenu();
readUserInput();
switch(userInput) {
case 1 :
//here you put your convMenu
do {
displayConvMenu();
readUserInput();
switch(userInput) {
case 1, 2, 3 :
doConvertion();
case 4 :
exitConvMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitConvMenu)
case 2:
exitMainMenu = true;
default :
//wrong input display a message and loop
}
} while(!exitMainMenu)
Breaking down the code in little pieces usually makes it easier to understand and debug. Divide and conquer! Here is how I would do it:
First create a Menu class which represent a menu, it can print the Menu on screen and check that a choice is valid:
class Menu {
private String title;
private List<String> choices;
private String prompt;
public Menu(String title, List<String> choices, String prompt) {
this.title = title;
this.choices = choices;
this.prompt = prompt;
}
public boolean isChoiceAllowed(int i) {
return i > 0 && i <= choices.size();
}
public void show() {
System.out.println(title);
for(int i=0; i<choices.size(); i++) {
System.out.println(" " + (i+1) + ". " + choices.get(i));
}
System.out.println(prompt);
}
}
Then define your 2 menus:
private static final Menu mainMenu = new Menu(
"Main Menu",
Arrays.asList("Enter Distance", "Quit the program"),
"Please enter your choice");
private static final Menu conversionMenu = new Menu(
"Conversion Menu",
Arrays.asList("Convert to kilometers", "Convert to inches", "Convert to feet", "Return"),
"Please enter your choice");
Have a method to read the user input:
private static int readUserInput() {
int input = keyboard.nextInt();
// Check if input is valid, if not call back readUserInput() until a valid input is given
if(!currentMenu.isChoiceAllowed(input)) {
System.out.println("Please Enter a valid option");
return readUserInput();
}
return input;
}
Have a method to handle choices in the Main Menu
private static void handleMainMenuChoice(int choice) {
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
// Set the current menu to be the Conversion Menu
currentMenu = conversionMenu;
break;
case 2:
quitProgram();
break;
}
}
Have a method to handle choices in the Conversion Menu
private static void handleConversionMenuChoice(int choice) {
switch (choice) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
// Set the current menu to be the Main Menu
currentMenu = mainMenu;
break;
}
}
Have a method to handle the user choice and dispatch it to the appropriate method above:
private static void handleChoice(int choice) {
if(currentMenu == mainMenu) {
handleMainMenuChoice(choice);
} else {
handleConversionMenuChoice(choice);
}
}
Then tie it up together:
private static double meters;
private static Menu currentMenu;
private static Scanner keyboard = new Scanner(System.in);
<Insert menu definitions here>
public static void main(String[] args) {
currentMenu = mainMenu;
int choice;
while (true) {
// Show the current menu
currentMenu.show();
// Read the user input
choice = readUserInput();
// Handle the user choice
handleChoice(choice);
}
}
public static void main(String[] args) {
int choice = 0;
int option;
double meters = 0;
Scanner keyboard = new Scanner(System.in);
boolean exit = false;
while(!exit) {
System.out.println("\nEnter your choice :Enter Distance.. click1\r\n" +
"\r\n" +
"Quit the program.. click2");
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter a Distance in Meters:");
meters = keyboard.nextDouble();
System.out.println("Conversion Menu\r\n" +
"\r\n" +
"Convert to kilometers .. click1\r\n" +
"\r\n" +
"Convert to inches .. click2\r\n" +
"\r\n" +
"Convert to feet .. click3\r\n" +
"\r\n" +
"Return.... .. click4");
int choice1 = keyboard.nextInt();
switch(choice1) {
case 1:
showKilometers(meters);
break;
case 2:
showInches(meters);
break;
case 3:
showFeet(meters);
break;
case 4:
exit = true;
break;
}
break;
case 2:
exit = true;
break;
default:
break;
}
}
}

How do I go back to my previous menu?

I've looked at everything mentioned about this and if I make a do/while loop it will just repeat the selection. If I make them conditionals instead of a switch it gives me "NoSuchElementException: No line found". Now its also giving me a "NoSuchElementException: No line found" even though I am back to a switch. I just want to know what I'm missing in this code that will let the user back out their first selection (while loop) to make a different one. Here is the code:
public class Zoo {
static FileRead fr = new FileRead();
private static final Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
while (userChoice == 1) {
// Select Animal
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
userChoice = menu();
break;
} FileRead.readAnimal(Name);
}
while (userChoice == 2) {
// Select Habitat
int animal = habitatSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Habitat - Penguin";
break;
case 2:
Name = "Habitat - Bird";
break;
case 3:
Name = "Habitat - Aquarium";
break;
default:
userChoice = menu();
break;
}
FileRead.readHabitat(Name);
}
// Exit Program
if (userChoice == 3) {
System.out.println("Thank you!");
System.exit(0);
}
// Error for invalid option
else {
System.out.println("ERROR: Invalid Selection");
}
}
}
private static int habitatSelect() {
// Habitat Menu
System.out.println("Which habitat would you like to monitor?");
System.out.println("1. Penguin Habitat");
System.out.println("2. Bird Habitat");
System.out.println("3. Aquarium");
System.out.println("4. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int animalSelect() {
// Animal Menu
System.out.println("Which animal would you like to monitor?");
System.out.println("1. Lion");
System.out.println("2. Tiger");
System.out.println("3. Bear");
System.out.println("4. Giraffe");
System.out.println("5. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
private static int menu() {
// Main Menu
System.out.println("WELCOME! Plese choose from the following");
System.out.println("1. Monitor Animal");
System.out.println("2. Monitor Habitat");
System.out.println("3. Exit");
int userChoice = Integer.parseInt(scnr.nextLine());
return userChoice;
}
}
This all reads a from another file in the package. If that code is needed I will also post it.
Tweak your main method as below
public static void main(String[] args) throws FileNotFoundException {
while (true) {
int userChoice = menu();
switch (userChoice) {
case 1: // only for animals
int animal = animalSelect();
String Name = null;
switch (animal) {
case 1:
Name = "Animal - Lion";
break;
case 2:
Name = "Animal - Tiger";
break;
case 3:
Name = "Animal - Bear";
break;
case 4:
Name = "Animal - Giraffe";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (Name != null) // read file only if selection is correct
FileReader.readAnimal(Name);
break;
case 2: // only for habitat
int habitat = habitatSelect();
String habitatName = null;
switch (habitat) {
case 1:
habitatName = "Habitat - Penguin";
break;
case 2:
habitatName = "Habitat - Bird";
break;
case 3:
habitatName = "Habitat - Aquarium";
break;
default:
System.out.println("ERROR: Invalid Selection");
break;
}
if (habitatName != null) // read file only if selection is correct
FileRead.readHabitat(habitatName);
break;
case 3 : // only for exit
System.out.println("Thank you!");
System.exit(0);
default:
System.out.println("ERROR: Invalid Selection");
}
}
}
Thus after each sub-menu, the user is returned to the main menu. As for your exception, for now I have added a null check so that the file is read only if the selection is correct.
Also, note that the above code doesn't contain nested loop which increases the performance and also excludes (the slightly messy) recursive call.

program terminate after using try catch block in switch statement

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

Best practice to create two-level deep selection menu in Java console

I'm about to create an application that runs off the java console as opposed to the GUI, and I had a question about the best way to approach displaying menus with another level of a submenu. I've quickly typed up the below code to sort of give you an idea of what I'm attempting to achieve.
I'm aiming for the menus of modify account and access account to both open up sub-menus with further choices. Essentially I'm trying to de-clutter the application from having too many choices (e.g. Change Account ID, Change Account Balance, Change Account Nickname, etc).
I've seen some places around the internet that seem to dislike this type of "tree-like" structure. Is there any clean way of doing something like this, or would I be forced to do something like create individual methods (i.e. AccountMenu) which would display different prompts and essentially create yet another do while loop.
public class Console
{
public static void main (String[] args) {
System.out.println("Welcome to the console application");
int selection =0;
do
{
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
selection = ReadConsole.nextInt();
switch (selection)
{
case 1: dothislater; break;
case 2: dothislater; break;
case 3: dothislater; break;
case 4: System.out.println("Application has been shut down")
break;
default:
System.out.println("The selection was invaild!");
}
}while (selection != 4);
}
}
I'm new to java, and I'm simply doing this to fool around with what it's like. Suggestions / ideas? I should also mention that I don't want to implement a "proper" GUI like swing elements.
You could make for every (sub)menu another function.
The reason why this aint prefered is because it aint in the spirit of OOP.
public class Console {
private int testint = 1;
/**
* #param args
*/
public static void main(String[] args) {
Console console = new Console();
console = console.mainMenu(console);
System.out.println("Application has been shut down");
}
private Console mainMenu(Console console) {
System.out.println("Welcome to the console application");
int selection = 0;
do {
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
// selection = testint++;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console;
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
private Console submenu1(Console console) {
System.out.println("Welcome to the SUBMENU");
int selection = 0;
do {
System.out.println("[1] SUBMENU_1");
System.out.println("[2] SUBMENU_2");
System.out.println("[3] SUBMENU_3");
System.out.println("[4] Return");
System.out.print("Insert selection: ");
//selection = ++testint;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console.mainMenu(console);
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
}
Might need a bit more tweaking, but you might get the idea

Exception Handling not working

I made an ATM program. I have a try catch that will ask for the user to type in their pin number. The pin number must be 5 digits. So the exception will check if it is 5 digits or not but the exception handling is not working. No matter what number I type in, it always says invalid number.
Here is my code the try catch is at the top of the program and the exception handling checkNumber is at the bottom of the program..
import java.util.ArrayList;
import java.util.Scanner;
public class BankMain
{
private double availableBal = 80;
private double totalBal = 100;
private double availableBal2 = 480;
private double totalBal2 = 500;
private double availableBal3 = 80;
private double totalBal3 = 100;
ArrayList<Integer> cardNum = new ArrayList<Integer>();
static Scanner input = new Scanner(System.in);
private String error; // String the error from the exception
{
error = "error";
}
public void cardNumbers()
{
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
try
{
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
checkNumber();
}
catch (invalidNumber err)
{
System.out.println("Caught Error: " + err.getError());
}
System.out.println("Thank you! You're card number is " + cardNum);
System.out.println("Type 'c' to go back to main menu.");
String value = keyboard.next();
if (value.equalsIgnoreCase("c"))
{
menu();
}
else if (!keyboard.equals('c'))
{
System.out.println("Invalid Entry!");
}
}
public void menu()
{
System.out.println("ATM Menu:");
System.out.println();
System.out.println("1 = Create Account");
System.out.println("2 = Account Login");
System.out.println("3 = Exit ATM");
query();
}
public void startAtm()
{
menu();
}
public void drawMainMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch (selection)
{
case 1:
viewAccountInfo();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
public void viewAccountInfo()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $" + totalBal);
System.out.println("\t--Available balance: $" + availableBal);
drawMainMenu();
}
public void viewAccountInfo2()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $" + totalBal2);
System.out.println("\t--Available balance: $" + availableBal2);
drawMainMenu();
}
public void deposit(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal = totalBal + depAmount;
availableBal = availableBal + depAmount;
}
public void checkNsf(int withdrawAmount)
{
if (totalBal - withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal = totalBal - withdrawAmount;
availableBal = availableBal - withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
public void addFunds()
{
int addSelection;
System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection = input.nextInt();
switch (addSelection)
{
case 1:
deposit(20);
drawMainMenu();
break;
case 2:
deposit(40);
drawMainMenu();
break;
case 3:
deposit(60);
drawMainMenu();
break;
case 4:
deposit(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void withdraw()
{
int withdrawSelection;
System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection = input.nextInt();
switch (withdrawSelection)
{
case 1:
checkNsf(20);
drawMainMenu();
break;
case 2:
checkNsf(40);
drawMainMenu();
break;
case 3:
checkNsf(60);
drawMainMenu();
break;
case 4:
checkNsf(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void query()
{
Scanner keyboard = new Scanner(System.in);
double input = keyboard.nextInt();
if (input == 2)
{
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
BankMainPart2.loginCard(cardNum);
}
else if (input == 1)
{
cardNumbers();
}
else if (input == 3)
{
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
public void checkingMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch (selection)
{
case 1:
viewAccountInfo2();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
private static void checkNumber() throws invalidNumber // run the check activation exception
{
if (String.valueOf(input).length() != 5)
{
throw new invalidNumber("invalid number");
}
else
{
System.out.println("Works!");
}
}
public static void main(String args[])
{
BankMain myAtm = new BankMain();
myAtm.startAtm();
}
}
This code snippet looks fine:
if (String.valueOf(input).length() != 5)
{
throw new invalidNumber("invalid number");
}
else
{
System.out.println("Works!");
}
As long as you don't realize that input is not the double variable declared locally somewhere:
double input = keyboard.nextInt()
instead it's an instance of java.util.Scanner (!)
static Scanner input = new Scanner(System.in)
And Scanner.toString() is certainly not the PIN you want.
Why you are having three different instances of Scanner class.. That is what making the program confusing..
In the compareNumber() method, you are actually checking the value of input, which is an instance of Scanner.. It's better to use it like this: -
checkNumber(input.nextInt())
And add the number to the list in your checkNumber(int num) method..
Of course I am not saying that it is a good way of coding.. But it will solve your problem for the time being..
Else, there are so many issues with your code..
This is your try-catch block: -
try {
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
checkNumber();
} catch (invalidNumber err) {
System.out.println("Caught Error: " + err.getError());
}
And this is your checkNumber() method : -
private static void checkNumber() throws invalidNumber
{
if (String.valueOf(input).length() != 5) {
throw new invalidNumber("invalid number");
}
else {
System.out.println("Works!");
}
}
Now you must see that you are using input as a parameter to String.valueOf(input).
But you have declared 'input` as an instance of Scanner before your try-catch block..
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
This code is in your codeNumbers() method..
So, clearly your input can never actually contain a user input, rather a hashcode representing the object new Scanner(System.in).
So, its better that you pass the integer input from user to checkNumber() method..
************ MODIFICATION Needed in Code..
So, your checkNumber()` will be modified as: -
private static void checkNumber(int number) throws invalidNumber
{
if (String.valueOf(number).length() != 5) {
throw new invalidNumber("invalid number");
}
else {
System.out.println("Works!");
}
}
And your call to this method in try-catch block will change to this: -
try {
System.out.println("Please select a 5 digit card number");
int number = input.nextInt();
cardNum.add(number);
checkNumber(number);
} catch (invalidNumber err) {
System.out.println("Caught Error: " + err.getError());
}
Your code checks that String.valueOf(input) has a length of 5 characters. But input is not the number entered by the user. It's the object of type Scanner that is used to parse what the user enters. So the result of String.valueOf(input) is probably something like java.util.Scanner#B09876.

Categories