java - 使用扫描仪选择以前的用户输入

标签 java input

我正在测试一些代码,用户选择数字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/

相关文章:

html - 组合 HTML 数字和选择输入

c - 在 C 中使用文件作为输入

java - 从 java 代码连接 MS Access 数据源

c++ - 从 C++ 文件中读取 X 行到 Y 行

java - 如何将旧的 for 循环更改为 IntStream?

java - 是否可以在 Windows 中编写忽略所有形式的 SIGTERM 的批处理 [或其他可执行] 应用程序

java - 循环直到按下某个键 Java

javascript - 如何从键盘编辑时间选择器的值?

java - 如何优化我的 PrimeDivisor 函数

java - 并发java