我正在测试一些代码,用户选择数字0和1 - 3。1 - 3选择一个选项并将数字添加到总数中,0退出并打印最终总数。该代码似乎可以工作,但只能按顺序运行,例如:输入 1,2,3,0。我的问题是如何才能使用户可以在任何点输入任何选择,例如:2,2,3,0,然后打印最终总计。
import java.util.*;
import javax.swing.*;
public class Coffee {
public static void main(String[] args) {
double AmericanPrice;
double EspressoPrice;
double LattePrice;
double totalBill;
AmericanPrice = 1.99;
EspressoPrice = 2.50;
LattePrice = 2.15;
int selectionBill;
int selectionA;
int selectionE;
int selectionL;
selectionBill = 0;
selectionA = 1;
selectionE = 2;
selectionL = 3;
totalBill = 0.0;
Scanner user = new Scanner(System.in);
while(true) {
System.out.print("Place your order: ");
if(user.nextInt() == selectionA) {
totalBill = totalBill + AmericanPrice;
System.out.print("Place your order: ");
}
if(user.nextInt() == selectionE) {
totalBill = totalBill + EspressoPrice;
System.out.print("Place your order: ");
}
if(user.nextInt() == selectionL) {
totalBill = totalBill + LattePrice;
System.out.print("Place your order: ");
}
if(user.nextInt() == selectionBill) {
System.out.print("Total: "+totalBill);
break;
}
}
}
}
最佳答案
正如 JB 所说,调用 nextInt() 实际上“消耗”了输入,因此再次调用它会获取下一个输入。您想要的是调用它一次,然后进行比较,然后循环重复,如下所示:
int answer = user.nextInt();
while(answer != 0) {
if(answer == selectionA) {
...
}
if(answer == selectionB) {
...
}
answer = user.nextInt();
}
请注意,“switch ”可能比这里的 if 更好。
关于java - 使用扫描仪选择以前的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25469620/