如何解决索引匹配最大/最小分数Java
我正在完成一项编码作业,并且接近完成,除了我的最终打印语句需要匹配名称和最大值和最小值的分数。
我已经能够使用两个 if 语句在两个句子中获得适当的值,但我对如何使我的索引正确以将名称与分数 w/max 和 min 对齐有点难。
除了数组和索引之外,我无法使用类或其他/不同的方法。
//Create method StudentMax
private static int StudentMax(int[] scores) {
int scoreMax = scores[0];
for (int i = 0; i < scores.length; i++){
if (scores[i] > scoreMax){
scoreMax = scores[i];
}
}
return scoreMax;
}
//Create method StudentMin
private static int StudentMin(int[] scores) {
int scoreMin = scores[0];
for (int i = 0; i < scores.length; i++){
if (scores[i] < scoreMin) {
scoreMin = scores[i];
}
}
return scoreMin;
}
public static void main(String[] args) {
//Call Scanner
Scanner scan = new Scanner(system.in);
//User Welcome
System.out.println("Welcome to the student score sorter.");
System.out.println("\nThis program will accept a number of student names and score values,then find the highest and lowest score.");
System.out.println("\nThen will return the names and max/min scores.");
//User Prompt Enter number of students
System.out.println("\nHow many students would you like to enter: ");
int StudentCount = scan.nextInt();
//Create arrays: scores,StudentFirst,StudentLast
int [] scores = new int[StudentCount];
String [] StudentFirst = new String [StudentCount];
String [] StudentLast = new String [StudentCount];
for (int i = 0; i < scores.length; i++) {
System.out.println("\nStudent " + (i+1)+":");
System.out.println("\nEnter Student's name:");
StudentFirst[i] = scan.next();
StudentLast[i] = scan.next();
System.out.println("\nEnter Student's score (0-100):");
scores[i] = scan.nextInt();
}
int max = StudentMax(scores);
int min = StudentMin(scores);
for (int i = 0; i < scores.length; i++) {
System.out.println("\n"+StudentFirst[i] + " " + StudentLast[i] +": " + scores[i]);
}
for (int i = 0; i < scores.length; i++) {
if (scores [i] == max) {
System.out.println("\n"+ StudentFirst[i] +" "+ StudentLast[i] + " has the highest score => " +max+ " and " + StudentFirst[i]+" " + StudentLast[i]+ " has the lowest => " +min);
}
}
//This is the sentence format that I need to make work,but I am struggling to understand how to align the index for names and scores.
//System.out.println("\n"+StudentFirst[i] +" "+ StudentLast[i]+ " has the highest score => " +max+ " and " +StudentFirst[i] +" "+ StudentLast [i]+ " has the lowest score => " +min);
//Scan Close
scan.close();
//Close Program
}
}
解决方法
传回索引而不是值
private static int StudentMin(int[] Scores) {
int ScoreMin = Scores[0];
int index = 0;
for (int i = 0; i < Scores.length; i++){
if (Scores[i] < ScoreMin) {
ScoreMin = Scores[i];
index = i;
}
}
return index;
}
那你以后就可以用了
int index = StudentMax(Scores);
System.out.println("\n"+ StudentFirst[index] +" "+ StudentLast[index] + " has the highest score => " +Scored[index]);
注意请注意Java命名约定
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。