0

I'm learning Java right now, using the Blue Pelican Java book and Eclipse. I'm trying to write a simple bank account program, which takes the user's input for initial balance and account name, and I ran into a weird problem (which I have run into before, but finally decided to ask about): I can never get a string input after another input.

See here:

    //Get initial balance
    System.out.print("How much money do you want to open your account with? ");
    double accBalance = kbIn.nextDouble();

    //Get account name
    System.out.print("Who will this account belong to? ");
    String accName = kbIn.nextLine();

    //Create bank account
    BankAccount myAccount = new BankAccount(accBalance, accName);

When I have the two inputs in that order, the program accepts my input for the balance, but then immediately skips past the name input. At the end of the program, nothing is outputted for the name, as in The account balance is $1405.22 instead of The John Doe account balance is $1405.22

When I switch the two inputs, making the user input the name first and then the initial balance, it works perfectly. Why is this? What am I doing wrong?

ananaso
  • 167
  • 2
  • 15
  • use `double accBalance = Double.parseDouble(kbIn.nextLine());`. `NumberFormatException` will be thrown if input is unparsable – Smit Nov 20 '13 at 22:30

2 Answers2

2

nextDouble() does not advance to the next line where as nextLine() does. Use nextLine() in both cases and convert the string to the double. something like this.

Double.parseDouble(kbIn.nextLine());
Rayf
  • 451
  • 3
  • 12
0

After doing the kbIn.nextDouble(), the program takes the enter as the kbIn.nextLine() since the kbIn.nextDouble() only takes the double. To fix this, you can do

//Get initial balance
System.out.print("How much money do you want to open your account with? ");
double accBalance = kbIn.nextDouble();
kbIn.nextLine();

//Get account name
System.out.print("Who will this account belong to? ");
String accName = kbIn.nextLine();

//Create bank account
BankAccount myAccount = new BankAccount(accBalance, accName);
Dale22599
  • 337
  • 1
  • 2
  • 7