简体   繁体   中英

Java Do-While Loop - How to End the Program Using Q Option

so i have this simple bank program. it has main menus which are:

  • B - Check for Balance
  • D - Make Deposit
  • W - Make Withdraw
  • Q - Quit

their functions are basically their names. and there are two ways to terminate the program: by inputting 'Q' and 'N'.but I have a problem with the Q - Quit option. here's the source code:

Scanner scan = new Scanner (System.in);
        
    char anotherTransact = 0, option;
    int balance = 100000, deposit = 0, withdraw = 0;
    
    do {
    System.out.println("\nWelcome to ABC BANK \n");
    
    System.out.println("B - Check for Balance");
    System.out.println("D - Make Deposit");
    System.out.println("W - Make Withdraw");
    System.out.println("Q - Quit");
    
    
        System.out.print("\nSelect an option : ");
        option = scan.next().charAt(0);
        
        
        if ((option == 'B') || (option == 'b')) {
            System.out.println("\nYour current balance is " +balance);
        }
        
        else if ((option == 'D') || (option == 'd')) {
            System.out.print("\nEnter amount to Deposit : ");
            deposit = scan.nextInt();
            if (deposit > 1 && deposit <= 500000) {
                System.out.println("Deposit Transaction is successfully completed.");
                balance = balance + deposit; 
            }
            else if (deposit > 500000) {
                System.out.println("Deposit Amount must not be greater than 500,000");
            }
            else {
                System.out.println("Deposit must be greater than zero");
            }
        }
        
        else if ((option == 'W') || (option == 'w')) {
            System.out.print("\nEnter amount to Withdraw : ");
            withdraw = scan.nextInt();
            if ((withdraw % 100 == 0 && withdraw < 150000)) {
                System.out.println("Withdrawal Transaction is successfully completed.");
                balance = balance - withdraw;
            }
            else if (withdraw > 150000) {
                System.out.println("Withdrawal Amount must not be greater then 150,000");
            }
            else if (withdraw < 0) {
                System.out.println("Withdrawal Amount must be greater than zero");
            }
            else {
                System.out.println("Withdawal Amount must be divisible by 100");
            }
        }
        
        else if ((option == 'Q') || (option == 'q')) 
            break;
        
        else {
            System.out.println("\nInvalid entry, enter any valid option : (B/D/W/Q)");
        }
        
        
        System.out.print("\nWant to Transact another (Y/N?) ");
        anotherTransact = scan.next().charAt(0);
        
        System.out.println("\n======================================================"); 
    }
    
    
    while ((anotherTransact == 'Y') || (anotherTransact =='y'));
        if ((anotherTransact == 'N' || anotherTransact == 'n')) {
            System.out.println("\nThank you for using this program!");
        }
        else {
            System.out.println("Invalid entry, entery any valid option : (Y/N)");
        }
    scan.close();

and its output would be like this:

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option :

The output should be like this when i input the Q option:

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option : Q
======================================================

Thank you for using this program!

but when i input it, it would say that it is an invalid input. what should i do to end the program by inputting 'Q'?

Your Q implementation is correct, it will exit the do while loop, but after the while statement you have an if:

 if ((anotherTransact == 'N' || anotherTransact == 'n')) {
            System.out.println("\nThank you for using this program!");
        }
        else {
            System.out.println("Invalid entry, entery any valid option : (Y/N)");
        }

When you type Q to exit the loop anotherTransact is not equals to 'N' therefore it will go into the else and print invalid entry. If I understand correctly you dont actually need after the while statement is:

 System.out.println("\n======================================================"); 
 System.out.println("\nThank you for using this program!");

There are two problems with your code:

  1. Putting the following code outside the scope of do-while loop:

     if ((anotherTransact == 'N' || anotherTransact == 'n')) { System.out.println("\nThank you for using this program;"). } else { System.out,println("Invalid entry: entery any valid option; (Y/N)"); }

    However, just correcting this problem is not sufficient. Check the next point/problem to understand what needs to be done in order to get it working as per your expectation.

  2. Not looping back in case of invalid input: You need another loop (I recommend do-while loop as shown below) to rectify this problem.

     boolean valid; do { valid = true; System.out.print("\nWant to Transact another (Y/N?) "); anotherTransact = scan.next().charAt(0); System.out.println("\n======================================================"); if (anotherTransact == 'N' || anotherTransact == 'n') { System.out.println("\nThank you for using this program;"). } else if (.(anotherTransact == 'Y' || anotherTransact == 'y')) { System,out:println("Invalid entry; entery any valid option; (Y/N)"); valid = false; } } while (!valid);

The full updated code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        char anotherTransact = 0, option;
        int balance = 100000, deposit = 0, withdraw = 0;
        do {
            System.out.println("\nWelcome to ABC BANK \n");

            System.out.println("B - Check for Balance");
            System.out.println("D - Make Deposit");
            System.out.println("W - Make Withdraw");
            System.out.println("Q - Quit");

            System.out.print("\nSelect an option : ");
            option = scan.next().charAt(0);

            if ((option == 'B') || (option == 'b')) {
                System.out.println("\nYour current balance is " + balance);
            } else if ((option == 'D') || (option == 'd')) {
                System.out.print("\nEnter amount to Deposit : ");
                deposit = scan.nextInt();
                if (deposit > 1 && deposit <= 500000) {
                    System.out.println("Deposit Transaction is successfully completed.");
                    balance = balance + deposit;
                } else if (deposit > 500000) {
                    System.out.println("Deposit Amount must not be greater than 500,000");
                } else {
                    System.out.println("Deposit must be greater than zero");
                }
            } else if ((option == 'W') || (option == 'w')) {
                System.out.print("\nEnter amount to Withdraw : ");
                withdraw = scan.nextInt();
                if ((withdraw % 100 == 0 && withdraw < 150000)) {
                    System.out.println("Withdrawal Transaction is successfully completed.");
                    balance = balance - withdraw;
                } else if (withdraw > 150000) {
                    System.out.println("Withdrawal Amount must not be greater then 150,000");
                } else if (withdraw < 0) {
                    System.out.println("Withdrawal Amount must be greater than zero");
                } else {
                    System.out.println("Withdawal Amount must be divisible by 100");
                }
            } else if ((option == 'Q') || (option == 'q')) {
                break;
            } else {
                System.out.println("\nInvalid entry, enter any valid option : (B/D/W/Q)");
            }

            boolean valid;
            do {
                valid = true;
                System.out.print("\nWant to Transact another (Y/N?) ");
                anotherTransact = scan.next().charAt(0);

                System.out.println("\n======================================================");

                if (anotherTransact == 'N' || anotherTransact == 'n') {
                    System.out.println("\nThank you for using this program!");
                } else if (!(anotherTransact == 'Y' || anotherTransact == 'y')) {
                    System.out.println("Invalid entry, entery any valid option : (Y/N)");
                    valid = false;
                }
            } while (!valid);
        } while (anotherTransact == 'Y' || anotherTransact == 'y');
    }
}

A sample run:

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option : b

Your current balance is 100000

Want to Transact another (Y/N?) d

======================================================
Invalid entry, entery any valid option : (Y/N)

Want to Transact another (Y/N?) d

======================================================
Invalid entry, entery any valid option : (Y/N)

Want to Transact another (Y/N?) y

======================================================

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option : d

Enter amount to Deposit : 200
Deposit Transaction is successfully completed.

Want to Transact another (Y/N?) y

======================================================

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option : b

Your current balance is 100200

Want to Transact another (Y/N?) n

======================================================

Thank you for using this program!

Some additional side notes:

  1. You should never close the Scanner for System.in as it will also close System.in and there is no way to open it again without restarting the JVM. However, make sure to close a Scanner for a file.

  2. You should make a habit of enclosing the body of a block within {...} even if you have a single statement in the body. This will save you from some statement accidentally falling out of scope eg

    if (1 == 2) System.out.print("Hello"); System.out.println("World"); System.out.println("What's up?");

will print

World
What's up?

and not just

What's up?
  1. Keep your code well-formatted because it will help you find the problem easily and quickly. Your IDE can format the code on click of a button or when you press a combination of keys.

so i have this simple bank program. it has main menus which are:

  • B - Check for Balance
  • D - Make Deposit
  • W - Make Withdraw
  • Q - Quit

their functions are basically their names. and there are two ways to terminate the program: by inputting 'Q' and 'N'.but I have a problem with the Q - Quit option. here's the source code:

Scanner scan = new Scanner (System.in);
        
    char anotherTransact = 0, option;
    int balance = 100000, deposit = 0, withdraw = 0;
    
    do {
    System.out.println("\nWelcome to ABC BANK \n");
    
    System.out.println("B - Check for Balance");
    System.out.println("D - Make Deposit");
    System.out.println("W - Make Withdraw");
    System.out.println("Q - Quit");
    
    
        System.out.print("\nSelect an option : ");
        option = scan.next().charAt(0);
        
        
        if ((option == 'B') || (option == 'b')) {
            System.out.println("\nYour current balance is " +balance);
        }
        
        else if ((option == 'D') || (option == 'd')) {
            System.out.print("\nEnter amount to Deposit : ");
            deposit = scan.nextInt();
            if (deposit > 1 && deposit <= 500000) {
                System.out.println("Deposit Transaction is successfully completed.");
                balance = balance + deposit; 
            }
            else if (deposit > 500000) {
                System.out.println("Deposit Amount must not be greater than 500,000");
            }
            else {
                System.out.println("Deposit must be greater than zero");
            }
        }
        
        else if ((option == 'W') || (option == 'w')) {
            System.out.print("\nEnter amount to Withdraw : ");
            withdraw = scan.nextInt();
            if ((withdraw % 100 == 0 && withdraw < 150000)) {
                System.out.println("Withdrawal Transaction is successfully completed.");
                balance = balance - withdraw;
            }
            else if (withdraw > 150000) {
                System.out.println("Withdrawal Amount must not be greater then 150,000");
            }
            else if (withdraw < 0) {
                System.out.println("Withdrawal Amount must be greater than zero");
            }
            else {
                System.out.println("Withdawal Amount must be divisible by 100");
            }
        }
        
        else if ((option == 'Q') || (option == 'q')) 
            break;
        
        else {
            System.out.println("\nInvalid entry, enter any valid option : (B/D/W/Q)");
        }
        
        
        System.out.print("\nWant to Transact another (Y/N?) ");
        anotherTransact = scan.next().charAt(0);
        
        System.out.println("\n======================================================"); 
    }
    
    
    while ((anotherTransact == 'Y') || (anotherTransact =='y'));
        if ((anotherTransact == 'N' || anotherTransact == 'n')) {
            System.out.println("\nThank you for using this program!");
        }
        else {
            System.out.println("Invalid entry, entery any valid option : (Y/N)");
        }
    scan.close();

and its output would be like this:

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option :

The output should be like this when i input the Q option:

Welcome to ABC BANK 

B - Check for Balance
D - Make Deposit
W - Make Withdraw
Q - Quit

Select an option : Q
======================================================

Thank you for using this program!

but when i input it, it would say that it is an invalid input. what should i do to end the program by inputting 'Q'?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM