如何通过用户命令退出do-white循环,使程序停止要求更多用户输入?我试着在网上找到答案,但我尝试的解决方案都不适用。这是我下面的代码:
public double setExpenses() {
double total = 0;
Scanner expense = new Scanner(System.in);
System.out.println("Enter Expenses: ");
while (!expense.hasNextDouble()) {
System.out.println("Invalid Data Type. Please enter a numerical value."); //to prevent data types different from doubles
expense.next();
}
finished:
do { //supposed to continue asking for user input to add together...but how to end the loop?
double Expense = expense.nextDouble();
total += Expense; //adds user input together to total
System.out.println("Total Expenses so far: $" + total);
while (!expense.hasNextDouble()) {
if(expense.equals("done")) { //breaks loop if the user types "done"? idk if this is right.
break finished;
}
System.out.println("Invalid Data Type. Please enter a numerical value.");
expense.next();
}
}while (expense.hasNextDouble());
return total;
}
我认为这里的代码是:
if(expense.equals("done")) {//breaks loop if the user types "done"? idk if this is right.
break finished;
}
应更改为:
if(expense.next().equals("done")) { //breaks loop if the user types "done"? idk if this is right.
break finished;
}
原因是你会得到字符串值"完成",但你使用扫描仪"费用"进行比较。
希望得到帮助!