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

时间:2016-03-22 00:12:39

标签: 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"));
    }
}

程序工作正常,直到结束。如果我把钱存入其中并且到达线路"还有其他什么(Y或N)?"以后我不能输入任何东西;即使我有redo字符串。虽然如果我不存钱,我可以为redo输入一些东西,然后让程序循环。如何修复它,即使我存放东西也会循环?

1 个答案:

答案 0 :(得分:5)

原因有点棘手。这是因为在您调用 emails.put("sahaj9917730102@gmail", true); 之后,来自用户的in.nextDouble()仍然在输入流中,这样当您调用\nredo将等于空字符串。要解决此问题,请添加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);
    }