我有这个代码:
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
的东西并且可以让程序循环。我该如何修复它,以便即使我存入一些东西它也会循环?
最佳答案
原因有点棘手。这是因为在调用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);
}
或者另一种选择是:
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = Double.parseDouble(in.nextLine());
deposit(money);
}
关于Java,在 do-while 循环结束时不注册用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36144020/