gpt4 book ai didi

Java 循环让我大吃一惊

转载 作者:行者123 更新时间:2023-12-01 09:21:22 24 4
gpt4 key购买 nike

嗨,我在循环方面遇到了麻烦。我对如何设置获取方法感到困惑

  • 最低分

  • 最高分

  • 分数的平均值

如果未输入分数,则显示消息“未输入测试成绩分数”。

我还必须发送一个计数器(我这样做了),并且我还必须验证分数是否从 0 到 100(我这样做了),我只是不知道下一步该做什么

    import java.util.Scanner;

public class loops {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

int average = 0;
int count = 0;
int score;



System.out.print("Please enter first score:");
score = keyboard.nextInt();




while (score!=-1){

while ((score>=0)&&(score<=100)){

System.out.println("the score is between 0 to 100 ");
System.out.println("Please enter the next test score:");
score = keyboard.nextInt();
count = count + 1;

}


}


average = (score/count);
System.out.println("The average is " +average);
System.out.println("The number of test scores enter was:"+count);


}

}

最佳答案

查看评论中的解释:

import java.util.Scanner;

public class Loops { //use java naming convention

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

int count = 0, score = 0, min = 0, max = 0, sum =0;
float average = 0;//the average might not be int

System.out.print("Please enter first score:");
score = keyboard.nextInt();

//add it to sum
sum = score;
//keep first number as min and max
min = score; max = score;

count++;//increment counter

//this is not needed, score of -1 will stop the next loop any way
//while (score!=-1){

while (true){

System.out.println("the score is between 0 to 100 ");
System.out.println("Please enter the next test score, or -1 to quit:");
score = keyboard.nextInt();

if((score < 0) ||(score > 100)) {
break;
}
count++;//increment counter

//you need to sum all entered numbers
sum += score;

//check if entered number is min
if(score < min) {
min = score ;
}

//check if entered number is max
if(score > max) {
max = score ;
}
}

if(count >0 ) {
average = ((float)sum/count);
System.out.println("The average is " +average );
System.out.println("The min is " +min);
System.out.println("The max is " +max);
System.out.println("The number of test scores enter was:"+count);
}else {
System.err.println("No numbers entered");
}
}
}

如有需要,请随时要求澄清。

关于Java 循环让我大吃一惊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com