how to rerun switch case loop after some cases have already run - java

In this class of Bank ,there are basic functions of Bank , however the real problem is in the switch case loop.
class Bank{
private int Balance;
private int Withdrawal;
private int Deposit;
private int AccountNumber;
void Transaction(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the account number to whose account you want
to transfer money");
AccountNumber = input.nextInt();
System.out.println("Enter your current Balance");
Balance= input.nextInt();
}
void Display(){
System.out.println("Account number "+AccountNumber);
System.out.println("Balance is "+ Balance);
}
void deposit(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to deposit");
int n =input.nextInt();
Balance+=n;
}
void withdraw(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to withdraw");
int n =input.nextInt();
try {
if(n>Balance)
throw new Exception("The balance you have is insufficient");
}
catch(Exception e){
System.out.println(e);
}
}//void
I am trying to rerun the switch case loop, after inputing one value , i want it to ask user again all the options, i tried to use continue statement , but it shows error of continue outside the loop.Please help
public static void main(String args[])throws Exception{
Bank b1=new Bank();
Scanner input = new Scanner(System.in);
System.out.println("Enter the number corrosponding to your option ");
System.out.println("1 Set ");
System.out.println("2 Display ");
System.out.println("3 Deposit");
System.out.println("4 Withdraw");
System.out.println("5 Exit");
int num=input.nextInt();
switch(num){
case 1:
b1.Transaction();
//int c =input.nextInt();
//wants user to input value again so switch loop works
//again
break;
case 2:
b1.Display();
break;
case 3:
b1.deposit();
break;
case 4:
b1.withdraw();
break;
case 5:
return;
}
}//psvm
}

You could surround the switch in a
do{
int num=input.nextInt();
switch(num){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
return;
}
}while(num!=some_value_to_exit_switch);
}
}

I'd place the switch content in a while loop with a boolean flag, then it will re-run until you are satisfied with the input~

Related

Execution keeps timing out with this is 'do while' loop

I try to run this on the IDE and it just won't run.
Only inputting the number zero will run it.
Is it unable to leave the loop?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
do {
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
The initialization number should be done earlier. Here is the code:
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
Two changes: Move the scanner.nextInt() line inside do and change the while condition from number != 0 to number < 1 || number > 4:
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number < 1 || number > 4);
System.out.println("Exit");

How to make method inside method and catch the name of function above method in java which make the

import java.util.Scanner;
public class allPurpose {
public static void main(String[] args) {
theMain();
}
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void subtraction() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Subtraction\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a - b);
System.out.println("\n \t Subtraction: " + c);
System.out.println("\n!continue");
System.out.println("1. Subtraction");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
subtraction();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void multiplication() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Multiplication\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a * b);
System.out.println("\n \t Multiplication: " + c);
System.out.println("\n!continue");
System.out.println("1. Multiplication");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
multiplication();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void division() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Division\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a / b);
System.out.println("\n \t Division: " + c);
System.out.println("\n!continue");
System.out.println("1. Division");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
division();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void table() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Table\n");
System.out.print("Enter Number to get Table of it \t");
int a = sc.nextInt();
for (int i = 1; i<=10; i++){
int b = a*i;
System.out.println(a + " * " + (i) + " = " +b);
}
System.out.println("\n!continue");
System.out.println("1. Table");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
table();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void squareAndCube() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter one number to check its Square and Cube \t ");
int a = sc.nextInt();
int s = (a * a);
int c = (a * a * a);
System.out.println("\t Square: " + s + "\n \tCube: " + c);
System.out.println("\n!continue");
System.out.println("1. Square and Cube");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
squareAndCube();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void exit() {
System.out.println("\n \tThank you have a nice day ahead! :)");
}
}
I am making calculator in java with many features
We can see that I have added following code on every method
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
just the difference is second line of every method is different, in above example code its
System.out.println("1. Addition");
in above example its addition according to the method name (in Addition method it used so )
in subtraction method it is subtraction
and so on
so can we make one method to keep all of the above code and in that code also we do something which auto catch second line according to method in which we are using
like in division second line of it will System.out.println("1. Division"); which auto catch according to the method
First of all, System.out.println is not the only place where your methods differ, but also (more important) in case 1 of switch construct where each method recursively calls itself. Second, there is a problem with your design, whose solution will also solve the original problem. Notice that from each method you are calling another method, even in the case when user requested going back to Main Menu. Stack gets larger and larger! So let's first rewrite theMain method:
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
int n = 0;
while (n != 7) {
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
}
As you can see, we are in the loop which breaks in case that user wants to leave the program.
Now let's rewrite one of methods:
public static void addition() {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
if (!proceed("Addition"))
break;
}
}
And finally, code of proceed method:
public static bool proceed(String method) {
System.out.println("\n!continue");
System.out.println("1. " + method);
System.out.println("2. Main Menu");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
return true;
case 2:
return false;
default:
System.out.println("Invalid input");
break;
}
}
Notice that exit is now only possible from Main Menu.
Answer to your question - method name can be retrieved through reflection, but I believe that is an overkill for this simple program.
Consider using interfaces to make more generic methods; for example, addition/subtraction/multiplication and division can be modeled as one method as follows:
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator("Addition", (a,b) -> a+b);
break;
case 2:
doCalculator("Subtraction", (a,b) -> a-b);
break;
case 3:
doCalculator("Multiplication", (a,b) -> a*b);
break;
case 4:
doCalculator("Division", (a,b) -> a/b);
break;
The generic calculator which takes two inputs, and outputs one value:
public static void doCalculator(String title, Calculator calc) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected "+title+"\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = calc.calculate(a, b);
System.out.println("\n \t "+title+": " + c);
System.out.println("\n!continue");
System.out.println("1. "+title);
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator(title, calc);
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
sc.close();
}
The key is to use an interface which models the calculation:
interface Calculator {
int calculate(int a, int b);
}
You can create other interfaces which closely model other types of calculations to expand the flexibility of this approach.
You can avoid using reflection if you add a simple interface:
public class allPurpose {
//All current methods here
interface Action{
void doOption();
}
}
Then, just index into the array of your methods.
In theMain() you can do:
public static void theMain() {
//Other code here
//instead of switch statement do:
Action[] initialOptions = new Action[] {
new Action() { public void doOption() { addition(); } },
new Action() { public void doOption() { subtraction(); } },
new Action() { public void doOption() { multiplication(); } },
new Action() { public void doOption() { division(); } },
new Action() { public void doOption() { table(); } },
new Action() { public void doOption() { squareAndCube(); } },
new Action() { public void doOption() { exit(); } },
};
int n = sc.nextInt();
if(n < 1 || > 7)
System.out.println("Invalid input");
else
actions[n-1].doOption();
}
Use a helper method in the other methods, where repeat is the current method:
public static void continueOptions(int i, Action repeat){
Action[] options = new Action[] {
repeat,
new Action() { public void doOption() { theMain(); } },
new Action() { public void doOption() { exit(); } },
};
if(i < 1 || > 3)
System.out.println("Invalid input");
else
options[i-1].doOption();
}
After this, for example addition would look like:
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
continueOptions(int i, new Action() { public void doOption() { addition(); } });
}
You can pass a parameter to a method and use switch case inside that method :
public static void callthismethod(int number){
System.out.println("\n!continue");
switch (number) {
case 1 : System.out.println("1. Addition");break;
case 2 : System.out.println("1. Subtraction");break;
case 3 : System.out.println("1. Multiplication");break;
..............
..............
..............
}
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
switch (n) {
case 1:
if(number == 1){
addition();
}
else if(number == 2){
subtraction();
}
else if(number == 3){
multiplication();
}
...........
...........
...........
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}

How to write a go back code so after the user selects a case he/she can go back to the last option?

package thecashmachin;
import java.util.Scanner;
public class TheCashMachin {
public static void main(String[] args) {
int pin, proceed2=0, withdraw, dailydraw, Proceed, proceed3 = 0;
double balance;
Scanner pinnumber = new Scanner(System.in);
Scanner proc2 = new Scanner(System.in);
Scanner withd = new Scanner(System.in);
Scanner Next = new Scanner(System.in);
Scanner proc3 = new Scanner(System.in);
balance = 9999.99;
dailydraw = 1000;
System.out.println(
"text .");
System.out.println("1)Proceed");
System.out.println("2)Return Card");
Proceed = Next.nextInt();
switch (Proceed) {
case 1:// Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin = new Scanner(System.in);
int Pincode = Pin.nextInt();
if (Pincode > 9999 && Pincode < 99999) {
System.out.println("1)Display Balance");
System.out.println("2)Withdraw Cash");
System.out.println("3)Other services");
proceed2 = proc2.nextInt();
} else {
System.err.println(
"text");
}
break;
case 2:// Return Card
System.err.println("text");
break;
default:
System.err.println(
"text");
break;}
switch (proceed2) {
case 1:
System.out.println("Your balance today is: 9999.99");
/*
* so right here the balance is shown and in real life you would have a go back button to display the other options but on my code after the balance is displayed you cant do anything else have to re run the the script i want a code that if selected goes back to the last option*/
break;
case 2:
System.out.println("Amount to withdraw");
withdraw = withd.nextInt();
System.out.println("Please take the cash");
System.out.println("Current Balance" + " " + (balance - withdraw));
System.out.println("Daily withdraw left:" + (dailydraw - withdraw));
if (withdraw > dailydraw) {
System.err.println("text");
}
case 3:
System.out.println("Would you like to;");
System.out.println("1)Order a check");
System.out.println("2)Order a Statement");
proceed3 = proc3.nextInt();
break;
default:
System.out.println("text");
}
switch (proceed3) {
case 1:
System.out.println("Your check has been orderd");
break;
case 2:
System.out.println("Your Statement has been orderd");
break;
}
}
}
DO
BOOLEAN = TRUE;
SWITCH() // WITH THE DIFFERENT CASES
DEFAULT BOOLEAN = FALSE;
WHILE BOOLEAN IS FALSE;
This should do. Use a simple do while loop.
Before entering the switch, your boolean is set to TRUE and if it comes to the default it turns it to FALSE and you loop until the boolean stays TRUE
An easy way I know is just making a Boolean before which is kept same as default..
boolean test = True;
while (test)
{
switch(Proceed)
{
case 1://Proceed
System.out.println("Please enter your 5 digit pin below.");
Scanner Pin=new Scanner(System.in);
int Pincode=Pin.nextInt();
test = false;
break;
case 2://Return Card
System.err.println("Your card is being ejected.\n Please Wait..");
test = false;
break;
default:
System.err.println("Sorry your request could not be processed.\n Please enter the pin again.\n")
// when neither case is true, keeps loop running.
break;
}
}

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.

Exception Handling giving me trouble

I have a small program I am working on. I Just put a try catch in my code and everything seems to be working except for 1 thing. I will post my code below... As you can see my try catch statement in my code it tells the program to go down to the checkNumber method for exception handling. I keep getting an error on this part...
if (input == 5){
}
The input keeps underlining red and saying "Incompatible operand types scanner and int.
Not sure what the problem is... or how to fix it.. here is my code
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 (input == 5)
{
System.out.println("");
}
else
throw new invalidNumber("invalid number");
}
public static void main(String args[])
{
BankMain myAtm = new BankMain();
myAtm.startAtm();
}
}
Class Bank Main 2
import java.util.ArrayList;
import java.util.Scanner;
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
BankMain main = new BankMain();
AccountMain main3 = new AccountMain();
Scanner logNum = new Scanner(System.in);
int loginInput = logNum.nextInt();
if (cardNum.contains(loginInput)) {
main3.selectAccount();
}
else {
System.out.println("Sorry, that pin number is incorrect!");
}
}
}
Your variable input is an object of Scanner which is declared globally and will be used for the method checknumber() and 5 is an int. Hence they are incompatible types.
The same statement works for method query() because for query you have locally defined a variable input which is of the type double.
What you should actually write is
if(input.nextInt() == 5){}

Categories