1

I'm trying to make a "Bank Account" and that requires the user to input the name, password, balance, and interest of that bank account. I use a sentinel controlledwhile loop to achieve this, but my sentinel does not work for some reason. Here's part of my code, if you could help me that would be great:

    System.out.println("New Account: Enter name, type \"quit\" to exit. ");
    String name = scan.nextLine();
    while (!name.equals("quit")) {
        System.out.println("Enter password: ");
        String pass = scan.nextLine();
        System.out.println("Enter balance (in pennies): ");
        double bal = scan.nextDouble();
        System.out.println("Enter interest: ");
        double inter = scan.nextDouble();

        BankAccount2 bankacc = new BankAccount2(name, pass, bal, inter);
        accounts.add(bankacc);
        System.out.println("Successful account creation! New Account: Enter name, type        \"quit\" to exit. ");
        name = scan.nextLine();
    }

To clarify, the problem is that the first time when I enter "quit", before the loop starts, it works well and the loop does not begin. However, when I input a bank account, and it goes to "Enter name" all over again, when I type quit the loop does not stop.

Freedom
  • 336
  • 1
  • 6
  • 23

1 Answers1

2

I believe that the nextDouble() method does not read the next new line character. Check the documentation about this.

You might try calling nextLine() after calling nextDouble().

You can check the source of Scanner here. If you are stuck because of crappy javadoc or undocumented side effects I think it is always best if you check the code.

It seems that it is using a regex matcher which only matches a double pattern.

Adam Arold
  • 26,256
  • 18
  • 92
  • 176