嗨,我遇到了循环问题。我对如何建立一种获取方法的方法感到困惑
最低分
最高分
分数的平均值
如果未输入分数,则显示“未输入测试分数”的信息。
我还必须发送一个我做过的计数器,并且我还必须验证分数是否从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 - Java Loops踢了我的屁股,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40144692/