Java - 根据用户的回答询问问题 x 次

标签 java

我想根据答案问三个问题 x 次,然后我想根据给出的答案计算总成本。我想知道这种方式是否有效,如果有效,我如何计算总成本?

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("x ingredients?");
    int amount = sc.nextInt();

    for(int i = 1 ; i <= amount; i++) { 
        System.out.print("Nr " + i + ": How much do you have?\n");
        int have = sc.nextInt();
        System.out.print("Nr " + i + ": How much do you need?\n");
        int need = sc.nextInt();
        System.out.print("Nr " + i + ": How much does it cost?");
        int cost = sc.nextInt();
        if(i == amount) {
            // calculate total cost 
        }
    }   
}

最佳答案

您需要跟踪循环外的总成本,否则它将超出范围。例如,在循环之前,初始化总成本:

int totalCost = 0; //you used sc.nextInt() so I assume no decimals

然后,在循环中,只需获取购买数量并乘以成本即可。

int toBuy = need - have;
//you do NOT need if (i == amount) because you will add to the cost whenever it's necessary, not just at the end of the loop
if (toBuy > 0){ //don't buy things you don't need
    totalCost += toBuy * cost;
}

然后,在循环外打印总成本:

for (int i = 1; i <= amount; i++){
    //...
}
System.out.println("Total cost of ingredients: " + totalCost);

关于Java - 根据用户的回答询问问题 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413507/

相关文章:

java - 为什么我们在 Java PATH 变量中添加分号而不是在 JAVA_HOME 变量中添加分号?

java - 一些应用程序如何在 Android 上跟踪自己的卸载

java - Telnet Java 代码可以在 Windows 中运行,但不能在 Unix 中运行

java - 使用 GSON 将 JSONObject 转换为 JSON

java - 收缩字符串与使用原始字符串创建新字符串/编辑原始字符串时的程序效率

java - 使用 Gradle 运行 JUnit 时设置自定义安全管理器

java - MouseWheel 事件不会在 SWT-AWT 组件中触发

java - 项目监听器错误

java - 从 Java 文本文件中读取直到特定点

java - 在preparedstatement中创建自动增量id