我有这个程序,要求用户输入学生及其分数。然后显示得分最高和最低的学生姓名。我的问题是我的程序不会打印最低分数。
任何帮助将不胜感激。 下面是我的代码。
private Scanner n;
private int limit;
private String[] names;
private int[] scores;
public Exercise9() {
n = new Scanner(System.in);
limit = 0;
index();
}
public void index() {
int counter = 0;
System.out.print("Enter how many students : ");
limit = Integer.parseInt(n.nextLine());
names = new String[limit];
scores = new int[limit];
while(counter < limit && limit != 0) {
System.out.print("Enter name : ");
names[counter] = n.nextLine();
System.out.print("Enter score : ");
scores[counter] = Integer.parseInt(n.nextLine());
counter += 1;
}
if(limit == 0) {
System.out.print("\n\nNo student(s) to display .");
} else {
displayStudents();
}
}
public void displayStudents() {
System.out.print("\n\nDisplay list of student(s) and scores : \n");
for(int x = 0 ; x < limit ; x++) {
System.out.println("\t" + names[x] + "\t" + scores[x]);
}
System.out.print("\n\nHighest : " + getHighest() + "\t\tLowest : " + getLowest());
}
public String getHighest() {
int theScore = 0;
String theName = "";
for(int x = 0 ; x < scores.length; x++) {
if(scores[x] > theScore) {
theScore = scores[x];
theName = names[x];
}
}
return theName;
}
public String getLowest() {
int theScore = 0;
String theName = "";
for(int x = 0 ; x < scores.length; x++) {
if(scores[x] < theScore) {
theScore = scores[x];
theName = names[x];
}
}
return theName;
}
public static void main(String[] args) {
new Exercise9();
}
最佳答案
您首先在 getLowest()
中将变量 theScore
初始化为零。假设您不会获得负分,则该分数永远不会更新。
尝试将 theScore
初始化为任意高的数字。
关于java数组显示最低学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882960/