尝试制作一个数字平均程序,该程序将终止程序并显示“#”;' -1被输入到系统中

时间:2018-01-03 17:09:07

标签: java input average calculator

我一直试图掌握这个数字平均程序,基本上,它需要用户输入,一旦输入-1,它将平均所有这些输入。我正在努力寻找一种给出平均值的方法,因为它现在给出了奇怪的答案。

以下是代码:

import java.util.Scanner;

public class LoopingDemo1 {

    public static void main(String[] args) {
        String input = "";
        int num = 0;
        int sum = 0;
        Scanner in = new Scanner(System.in);
        int z = -1;
        int i = 0;
        int counter = 0;
        counter++;

        while (i <= 0) {
            System.out.println("Please input a number");
            input = in.nextLine();

            num = Integer.parseInt(input);

            if (num == z) {
                int average = sum / counter;
                System.out.println("Average value is: " + average);
            } else {
                sum += num;
            }

            //what does this operator do? sum = sum + num
        }

        counter++;
    }
}

如果违反任何规则,我会事先道歉。

1 个答案:

答案 0 :(得分:0)

试试这个

int counter = 1;
while (true) {

    System.out.println("Please input a number");
    input = in.nextLine();

    num = Integer.parseInt(input);

    if (num == z) {
        double average = (double)sum / counter;
        System.out.println("Average value is: " + average);
        break;
    } else {
        sum += num;
        counter++;
    }

}