java - 用户输入仅发生一次或在循环期间永不停止

标签 java while-loop do-while

我正在尝试一个程序,它读取未指定数量的整数,查找总和、正数、负数和平均值。我的问题是,要么它只运行并允许输入一个整数,然后什么都不做,要么使用下面的代码,它永远不会停止让你输入数字,因此我无法通过。我的 number = 0 输出正确。

public class Compute {

// Count positive and negative numbers and compute the average of numbers
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int sum = 0;
        positive = 0;
        negative = 0;
        total = 0;

        System.out.println("Enter an integer, the input ends if it is 0: ");
        int numbers = input.nextInt();

        do {
            if (numbers > 0) {
                positive++;//add 1 to positive count
            } else if (numbers < 0) {
                negative++;//add 1 to negative count
            }//end else if

            sum += numbers; //add integer input to sum

            numbers = input.nextInt();
            total++;
        } while (numbers != 0);

        if (numbers == 0) {
            System.out.println("No numbers are entered except " + numbers);
        }//end if
    }
}

最佳答案

尝试下面的代码。终止循环并在执行的任何时候将输出类型 0 视为输入。

import java.util.Scanner;

public class Compute {

    // Count positive and negative numbers and compute the average of numbers
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int sum = 0;
        int positive = 0;
        int negative = 0;
        int total = 0;

        System.out.println("Enter an integer, the input ends if it is 0: ");
        int numbers = input.nextInt();

        do {

            if (numbers > 0) {
                positive++;// add 1 to positive count
                sum += numbers; // add integer input to sum
            }

            else if (numbers < 0) {
                negative++;// add 1 to negative count
                sum -= numbers; // add integer input to sum
            }

            numbers = input.nextInt();
            total++;

        } while (numbers != 0);

        System.out.println("The number of positives is \t " + positive);
        System.out.println("The number of negatives is \t " + negative);
        System.out.println("The total count of number is \t " + total);
        System.out.println("The sum of all number is    \t" + sum);
        System.out.println("The average is           \t"
                + ((double) sum / (positive + negative)));

    }// end main
}// end Compute

关于java - 用户输入仅发生一次或在循环期间永不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765363/

相关文章:

java 什么更重 : Canvas or paintComponent()?

Java:按照出现的顺序获取字符串中的分隔符

c# - 如何正确编写这个函数?每次都让我失忆

具有两个条件的 Java Do While 语句

c# - 我可以将这个 do-while 循环重写为 foreach 循环吗?

java - 更改 JTabbedPane 边框的颜色

java - 本地tomcat服务器返回405 Method Not allowed

python - 如何在每个循环后添加一个新行?

linux - 如何处理 shell 登录脚本中的错误密码?

c - 在 while 循环中反转 printf 函数的输出