0

I have this code:

import java.util.*;

public class MyAccount {
    public static double balance = 0.0;

    public static double deposit(double deposit){
        return balance += deposit;
    }
    //public void setBalance(double balance){
    //  this.balance = balance;
    //}
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String redo = "";
        do{
        System.out.println("What do you want to do today?");
        String answer= in.nextLine();
        if(answer.equals("deposit")){
            System.out.println("How much do you want to deposit?");
            double money = in.nextDouble();
            deposit(money);
        }
        System.out.println("Your balance is " + balance);
        System.out.println("Anything else(Y or N)?");
        redo = in.nextLine().toUpperCase();
        } while(redo.equals("Y"));
    }
}

The program works just fine up until the end. If I deposit money into it and reach the line "Anything else(Y or N)?" I can not enter anything after; even though I have the redo String there. Though if I don't deposit money, I can enter something for redo and can get the program to loop. How do I fix it so it loops even when I deposit something?

Maljam
  • 6,048
  • 3
  • 14
  • 30

1 Answers1

5

The reason is somewhat tricky. It's because after you call in.nextDouble(), the \n from the user is still in the input stream, such that redo will be equal to an empty String when you call redo = in.nextLine().toUpperCase(). To fix it, add in.nextLine() like so:

    if(answer.equals("deposit")){
        System.out.println("How much do you want to deposit?");
        double money = in.nextDouble();
        in.nextLine();
        deposit(money);
    }

Or another alternative is:

    if(answer.equals("deposit")){
        System.out.println("How much do you want to deposit?");
        double money = Double.parseDouble(in.nextLine());
        deposit(money);
    }
Maljam
  • 6,048
  • 3
  • 14
  • 30