提问人:andrewbauxier 提问时间:12/8/2022 最后编辑:David Buckandrewbauxier 更新时间:12/8/2022 访问量:38
Java,将数组传递到方法中并尝试返回索引,出现各种问题 [已关闭]
Java, passing an array into a method and attempting to return index, various issues arise [closed]
问:
我必须创建两个包含团队名称和团队分数的数组,将它们传递给不同的方法,找到最小值和最大值,打印出团队列表,并使用最高和最低分数进行评分。很酷,几乎都做得很好。
import java.util.*;
public class asgn6 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("\nHow many teams do you want to enter: ");
int teamNum = scanner.nextInt();
scanner.nextLine();
String[] team = new String[teamNum];
int[] score = new int[teamNum];
for(int i=0; i<teamNum; i++) {
System.out.println("Team " + ((i)+1) + ": \nEnter team's name:\t");
team[i] = scanner.nextLine();
System.out.println("Enter team's score (400-1000):");
score[i] = scanner.nextInt();
scanner.nextLine();
}
for (int i=0; i<teamNum; i++) {
System.out.println(team[i] + " " + +score[i]);
}
System.out.println("Losing team: " + team[minIndex] + " score: " + score[minIndex]);
System.out.println("Winning team: " + team[maxIndex] + " score: " + score[maxIndex]);
}
public static int findIndexOfMin (int[] score) {
int smallestValue = score[0];
int minIndex = 0;
for (int i = 0; i < score.length; i++){
if (score[i] <= smallestValue){
smallestValue = score[i];
minIndex = i;
}
}
return minIndex;
}
public int findIndexOfMax(int[] score) {
int largestValue = score[0];
int maxIndex = 0;
for (int i = 0; i < score.length; i++){
if (score[i] >= largestValue){
largestValue = score[i];
maxIndex = i;
}
}
return maxIndex;
}
}
当我尝试将索引从每个方法传递回 main 时,问题就开始了。它告诉我 和 的变量无法解析。我试图解决这些多种方法,但这通常只会导致它们默认为相同的值(据我所知,情况并非如此),或者只是在某种程度上完全错误。我无法弄清楚我在这里错过了什么。minIndex
maxIndex
答:
1赞
andrewbauxier
12/8/2022
#1
感谢 Robby Cornelissen。我未能实际调用方法并正确引用返回的索引。
findIndexOfMin(score);
findIndexOfMax(score);
System.out.println("Losing team: " + team[findIndexOfMin(score)] + " score: " + score[findIndexOfMin(score)]);
System.out.println("Winning team: " + team[findIndexOfMax(score)] + " score: " + score[findIndexOfMax(score)]);
aa 67
ss 45
dd 78
ff 13
gg 90
The gg have the highest score of => 90 and the ff have the lowest score of =>13
这成功了。将返回索引,然后显示引用列表的正确值。
评论
findIndexOfMin()
findIndexOfMax()