程序成功编译并运行。 然而,最低分的价值是错误的,我再次检查,不知道为什么 请帮我解决这个问题
/* import neccessary component for the program*/
import java.util.*;
public class assign4 {
/* create a input stream*/
static Scanner console = new Scanner(System.in);
public static void main(String[]args) {
/* declare variables and strings*/
int[] score;
score = new int[10];
String[] name;
name = new String[10];
String header = String.format("%10s%10s%8s%n", "Name", "Score", "Grade");
int min = score[0];
int max = score[0];
char grade[];
grade = new char[10];
int maxindex = 0;
int lowindex = 0;
for (int i = 0; i <= 9; i++) {
/* Get user's input for student's name and score*/
System.out.println("Please enter the student's name.");
name[i] = console.nextLine();
System.out.println("Please enter the student's score.( 0-100 )");
score[i] = console.nextInt();
if (score[i] > 80) {
grade[i] = 'A';
} else if (score[i] > 65) {
grade[i] = 'B';
} else if (score[i] > 40) {
grade[i] = 'C';
} else if (score[i] > 20) {
grade[i] = 'D';
} else {
grade[i] = 'E';
}
/* when the score is higher than the score, it become maximum score*/
if (score[i] > max) {
max = score[i];
maxindex = i;
} /* when the score is lower than the score, it become minimum score*/ else if (score[i]
< min) {
min = score[i];
lowindex = i;
} /* when the score neither lower or higher than the score, it will be ignored and program
do nothing*/ else {}
/* avoid scanner skipping in order to capture user's input */
console.nextLine();
}
/* print out the stored information of the students and show higest and lowest score */
System.out.println();
System.out.print(header);
for (int i = 0; i <= 9; i++) {
System.out.printf("%10s%10d%8s%n", name[i], score[i], grade[i]);
}
System.out.printf("%s obtains lowest score of %d%n", name[lowindex], min);
System.out.printf("%s obtains higest score of %d%n", name[maxindex], max);
}
}
该计划的目的是收集10人的分数和名称,然后打印出姓名,分数,最高分,最低分和分数。 此外,我只是加入这个网站,如果我提出的方法和问题是错误的,请告诉我,对不起
答案 0 :(得分:1)
您初始化int min = score[0];
将为0,因为score
是int[]
,每个条目的默认值为0。
您可能没有得到低于0的任何分数,因此if(score[i]<min)
仅对负值有效。尝试使用min
初始化Integer.MAX_VALUE
。
最好使用max
初始化Integer.MIN_VALUE
,但在您的情况下无关紧要。