mercredi 16 septembre 2020

if branches within while loop not executing as expected [closed]

Here is the code that I am working with. The other classes that are referenced here have been tested and work though they should not have an effect on the functionality of the statements here.

import java.util.Scanner;

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

        double transferAmount;
        Account acct1 = new Account(100, null);
        Account acct2 = new Account(100, null);


        System.out.print("Choose an option: "
                + "\n1 <Enter>: to transfer from account 1 to account 2"
                + "\n2 <Enter>: to transfer from account 2 to account 1"
                + "\n3 <Enter>: to quit");
        int userOption = scan.nextInt();
        scan.nextLine();

        while(userOption != 3); 
        {
            if (userOption == 1)
            {
                System.out.print("You chose transfer from account 1 to account 2"
                        + "\nEnter an amount to transfer: ");
                transferAmount = scan.nextInt();
                acct1.transfer(acct2, transferAmount);
            }
            else if (userOption == 2)
            {
                System.out.print("You chose transfer from account 1 to account 2"
                        + "\nEnter an amount to transfer: ");
                transferAmount = scan.nextInt();
                acct2.transfer(acct1, transferAmount);
            }
            else if (userOption == 3)
            {
                System.out.println(acct1.toString());
                System.out.println(acct2.toString());
            }
            else
            {
                System.out.println("Invalid input");
            }

            System.out.print("Choose an option: "
                    + "\n1 <Enter> to transfer from account 1 to account 2?"
                    + "\n2 <Enter> to transfer from account 2 to account 1"
                    + "\n3 <Enter> to quit");
            userOption = scan.nextInt();
            scan.nextLine();
        }

        System.out.println(acct1.toString());
        System.out.println(acct2.toString());
        scan.close();
    }

}

What I'm wanting this to do is prompt a user to choose one of the three options denoted by a numerical value. Then follow the if branch of that value, asking the user for an amount in the case of 1 or 2. Not exiting the while loop until the user chooses option 3. Whats happening is that when 3 or a value outside the specified range is entered the program works as expected, but when 1 or 2 are chosen as options nothing happens, not even the print statements are output. Any help with getting this working is much appreciated.

Aucun commentaire:

Enregistrer un commentaire