我正在完成一项编码任务,即将完成我的最终打印报表的保存,该报表需要匹配最大值和最小值的名称w/scores。
我已经能够使用两个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命名约定