执行While循环,跟踪用户输入Java

时间:2018-09-20 04:50:27

标签: java loops

如何跟踪用户输入并选择最大和最小?我也不允许在代码中放入数组,所以我需要if语句。我试过嵌套if语句,但当它不断变化时,我不知道如何比较用户输入的数字。我已经能够打印出一些结果,但是通常以我输入的最后一个数字作为输出结果。一些帮助将不胜感激。

    Scanner scan = new Scanner(System.in);

    double sum = 0;
    int totalnumber = 0;
    double avg = 0;
    double input;
    double num = 0;
    double large = 0;
    double small = 0;

    do{
        System.out.println("Please type in a number. Type 0 to quit.");
        input = scan.nextDouble();
        scan.nextLine();



        if(input == 0)
        {
            break; //breaks the loop when the user enters 0
        }
        else
        {
            totalnumber += 1; //tracker for how many times user enters a number
            sum+= input; //get the sum of the entered inputs
            //large = input;
            //small = input;
            //num = input;


        }
    }while(true);


    avg = sum / totalnumber; //getting the average of the inputs

    if(totalnumber == 0) //if the user only put in 0
    {
        System.out.println("You didn't type anything in.");
    }
    else //if the user entered 1 or more numbersk
    {
        System.out.println("The sum of your inputs is: " + sum);
        System.out.println("The total number of inputs you provided was: " + totalnumber);
        System.out.println("The average of your inputs is: " + avg);
        System.out.println("The highest number you input was: " + large);
        //System.out.println("The lowest number you input was: " + small);
    }
}

}

1 个答案:

答案 0 :(得分:2)

您可以使用Math.maxMath.min方法。

在执行此操作之前,请将值设置为

int large = Math.MIN_VALUE;
int small = Math.MAX_VALUE;
// above do not need to be doubles

{
    totalnumber += 1; //tracker for how many times user enters a number
    sum+= input; //get the sum of the entered inputs
    large = Math.max (large, input);
    small = Math.min (small, input);
}