Java,在do-while循环结束时不注册用户输入

Jok*_*313 0 java input while-loop

我有这个代码:

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

该程序工作正常,直到结束.如果我把钱存入它并达到"其他任何东西(Y或N)?" 以后我不能输入任何东西; 即使我在redo那里有弦乐.虽然如果我不存钱,我可以输入一些东西,redo并可以让程序循环.如何修复它,即使我存放东西也会循环?

Mal*_*jam 5

原因有点棘手.这是因为在您调用之后in.nextDouble(),\n来自用户的仍然在输入流中,这样redo在调用时将等于空字符串redo = in.nextLine().toUpperCase().要修复它,添加in.nextLine()如下:

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

或另一种选择是:

    if(answer.equals("deposit")){
        System.out.println("How much do you want to deposit?");
        double money = Double.parseDouble(in.nextLine());
        deposit(money);
    }
Run Code Online (Sandbox Code Playgroud)