java - 尝试计算使用 do-while 和 while 循环给出的输入的平均值,但它一直停止

标签 java while-loop average do-while

脚本的主要要点是不断询问成绩,直到用户输入负数。输入负数后,它会计算这些成绩的平均值。用户输入的成绩只能是4-10。

我已经花了几个小时试图解决这个问题。如果我只输入无效输入或只输入有效输入,它工作正常,但第二次我尝试将其混合时,脚本停止。

例如:如果我输入 4(有效输入),脚本会要求另一个成绩。如果我输入 3(无效输入),脚本会说输入无效并要求另一个有效输入。之后,如果我再次输入 4,它就会停止工作,而它应该会一直这样下去,直到我输入一个负数,它才会开始计算有效输入的平均值。

import java.util.Scanner;

public class Average {

public static void main(String[] args){

    Scanner scanner = new Scanner(System.in);

System.out.println("The program will calculate the average of the user inputted grades.");
System.out.println("The program will start calculating with any negative integer");

double grade;   
double sum = 0;
int count = 0;



do {
    System.out.print("Input grade (4-10): ");
    grade = scanner.nextDouble();

    if (grade >= 4 && grade <= 10){
        sum = sum + grade;
        count++; 
    }



} while (grade >= 4 && grade <= 10);

 {


while (grade >= 0 && grade < 4 || grade > 10){

    System.out.println("Invalid grade!");
    System.out.print("Input grade (4-10): ");
    grade = scanner.nextDouble();


    if (grade < 0){

        System.out.println(count + " grades were given.");
        System.out.println("Average: " + sum/count);
        break;
    }
  }
 }
} 

最佳答案

它不起作用,因为你的循环是分开的,所以如果 first 为假,则 second 只工作一次然后停止。尝试这样的事情:

import java.util.Scanner;

public class Average {

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);

        System.out.println("The program will calculate the average of the user inputted grades.");
        System.out.println("The program will start calculating with any negative integer");

        double sum = 0;
        int count = 0;
        double grade;

        do{
            System.out.print("Input grade (4-10): ");
            grade = scanner.nextDouble();

            if(grade >= 4 && grade <= 10){
                    sum = sum + grade;
                    count++;
            }else{
                System.out.println("Invalid grade!");
            }
        }while(grade >= 0);

        System.out.println(count + " grades were given.");
        System.out.println("Average: " + sum/count);


    }
}

关于java - 尝试计算使用 do-while 和 while 循环给出的输入的平均值,但它一直停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174167/

相关文章:

php - 使用php + MySQLi取数据时使用while可以吗?

MySQL AVG 函数给出的小数比预期多

arrays - 平均阵列Powershell的一部分

java - 如何使 JFrame 透明?

java - 当使用RabbitMQ作为java工作队列时,应该如何处理并发和 transient 错误?

java - 更新JRE后双击jar文件不会执行

java - 在 Android 中的 Fragment 中使用 WebView 时,页面显示未格式化的文本

Java while 循环没有按预期工作

c - 如何提示用户输入一定数量以内的整数

java - 如何在java面向对象编程中使用动态数组?