我正处于Java开始课程中,并且在从用户输入中提取数据并使用它根据用户输入量创建一组成绩时遇到问题。然后,我决定将这组数据从最高到最低组织起来并将其平均化。这是我到目前为止的代码
//import Scanner
import java.util.Scanner;
public class Looper {
public static void main(String[] args) {
//introduce integers
int highest = 0;
int lowest = 0;
int count = 0;
int grade = (int) (Math.random() * 100);
int student;
int total = 0;
double average = 0;
//introduce Scanner
Scanner input = new Scanner(System.in);
//printout number of students
System.out.println("Enter number of students");
student = input.nextInt();
//narrow amount of students
if (student <= 10) {
System.out.println("Enter the grades of the students");
}
else if (student >= 11) {
System.out.println("Too many Students");
}
//close off 0
while (student != 0) {
System.out.println("Didn't enter students");
}
grade = input.nextInt();
//connect student and grade
for (grade = 0; grade <= 100; grade++) {
student = grade;
if (grade > 100) {
System.out.println("Must be between 0 and 100")
} if (grade <= highest) {
grade++;
}
}
for (grade = 0; grade >= 0; grade++) {
student = grade;
if (grade < -1) {
System.out.println(" Must be between 0 and 100");
}
else if (grade >= lowest) {
grade++;
}
// form total and average
total = total + grade;
grade++;
{
average = (double) total / grade;
//printout highest, lowest, and average
System.out.println("The highest is" + highest + "\n The lowest is" + lowest + "The average is\n" + average);
}
}
}
}
答案 0 :(得分:1)
首先,使用不带括号的ifs会导致代码可读性差。
其次,;
之后System.out.println("Must be between 0 and 100")
丢失,而你的while循环后有;
:while (Student!= 0);{
当你的变量以小写字母开头时,你的变量都以大写字母开头。
此行之后有一个;
加倍int Grade= (int) (Math.random() *100);;
。//introduce scanner
//introduce integers
int highest = 0;
int lowest=0;
int count=0;
int Grade= (int) (Math.random() *100);;
int Student;
int Total=0;
double average= 0;
//print out number of students
Scanner input = new Scanner(System.in);
您的代码中的注释也没有任何意义....
import java.util.Scanner;
public class Looper {
public static void main(String[] args) {
int highest = 100;
int lowest = 0;
int grade = 0;
int students = 0;
float total = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
students = input.nextInt();
if (students <= 10) {
System.out.println("Enter the grades of the students: ");
// ADDED CODE
for(int i = 0; i < students; i++) {
do {
grade = input.nextInt();
if(grade >= 0 && grade <= 100) {
System.out.println("Grade must be between 0 and 100");
}
} while(grade < 0 || grade > 100);
if(grade > highest) {
highest = grade;
}
if(grade < lowest) {
lowest = grade;
}
total += grade;
}
average = (total/students);
System.out.println("The highest is " + highest);
System.out.println("The lowest is " + lowest);
System.out.println("The average is " + average);
// END ADDED CODE
} else if (students >= 11) {
System.out.println("Too many Students");
}
}
}
扫描仪介绍方式低于您的评论,您不打印学生人数,但输入学生人数......
我很抱歉,但这段代码很乱,我甚至不知道从哪里开始。
编辑:我对您的原始代码进行了一些重构,这应该会让您走上正确的道路。
{{1}}