java - 如何将用户输入的0或负数后输入的所有内容相加?!使用 do-while 语句

标签 java

import java.util.Scanner;
public class CashRegisterSimulation {

static Scanner console = new Scanner(System.in);    
    public static void main(String[] args) {

        int total = 0 , num;

        /*
         * Create a program that will ask the user to enter a series of amounts. 
         * Assume that the user is allowed to enter positive numbers only. If the 
         * user entered a value of 0, the program will stop asking for numbers and 
         * should display the sum of the inputs given. Use DO WHILE Loops.
         */

            do
            {
            System.out.print("Enter amount : ");
            num = console.nextInt();
                if(num <= 0)
                {
                    System.out.println("STOP");
                    total = total + num;
                    System.out.println("The total amount is : " + total);
                }
            } while (num > 0);
    }
}

如何让我的程序添加用户在输入 0 或负数后输入的所有输入?!

最佳答案

您想要在每次迭代中添加 num > 0 的总和:

    do
    {
      System.out.print("Enter amount : ");
      num = console.nextInt();
      if(num > 0)
      {
          total = total + num;
      }
    } while (num > 0);
    System.out.println("STOP");
    System.out.println("The total amount is : " + total);

关于java - 如何将用户输入的0或负数后输入的所有内容相加?!使用 do-while 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712877/

相关文章:

java.util.Map.put(key, value) - 如果值等于现有值怎么办?

java - 菜单项回调不起作用

java - Java中获取数组中的位置

java - 如果输入中包含数组中的某些内容,如何用数组中的元素替换输入中的字符串序列?

java - 用于下载 Java JDK Windows 的 Python 脚本

java - 如何在wave文件编辑器中面对java堆内存不足错误

java - Windows 和 Mac 上的 Android 库项目

java - 配置 Manuel 容器 IntelliJ Arquillian Wildfly

Java驱动程序按时间戳删除分区

java - Spring-Roo 删除 Mysql,尽管 hibernate.hbm2ddl.auto