对这些线程中的另一个感到抱歉,但正在阅读那里的内容,但没有任何内容回答我的问题。我有一些非常基本的代码,只接受 5 个值,对它们进行排序,并对中间的 3 个值进行一些数学计算,最后输出一些内容。不难,但由于某种原因,我的 Array.sort 只返回值 0。我很确定数组中的所有点在排序之前都已填充,并且我的数组大小正确。建议?
import java.util.*;
import java.util.Arrays;
public class practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int[] finals = new int[3];
int[] scores = new int[5];
int difficulty = 0;
for (int x = 0; x < 3; x++) {
System.out.println("Please input the scores for diver " + (x + 1));
for (int y = 0; y < 5; y++) {
scores[x] = scanner.nextInt();
System.out.println(scores[x]);
}
Arrays.sort(scores);
for (int j = 0; j < 5; j++) {
System.out.println(scores[x]);
}
System.out.println("Please input the difficult of diver " + (x + 1));
difficulty = scanner.nextInt();
finals[x] = (((scores[1] * scores[2] * scores[3]) / 3) * difficulty);
System.out.println(finals[x]);
}
winner(finals);
}
public static void winner(int[] finals) {
System.out.println(finals[0]);
if (finals[0] > finals[2] && finals[0] > finals[1]) {
System.out.println("Diver 1 is the winner of the olympics with a score of " + finals[0]);
} else if (finals[1] > finals[2] && finals[1] > finals[0]) {
System.out.println("Diver 2 is the winner of the olympics with a score of " + finals[1]);
} else if (finals[2] > finals[0] && finals[2] > finals[1]) {
System.out.println("Diver 3 is the winner of the olympics with a score of " + finals[2]);
} else {
System.out.println("There was a tie");
}
}
}
最佳答案
这个,
for (int y = 0; y < 5; y++) {
scores[x] = scanner.nextInt();
System.out.println(scores[x]);
}
应该是
for (int y = 0; y < scores.length; y++) {
scores[y] = scanner.nextInt();
System.out.println(scores[y]);
}
不要依赖硬编码长度。并记下您正在迭代的变量。。您在这里犯了一个非常类似的错误
for (int j = 0; j < 5; j++) {
System.out.println(scores[x]);
}
应该是
for (int j = 0; j < scores.length; j++) {
System.out.println(scores[j]);
}
关于java - Array.sort 只返回 0 个值。数组大小正确并且数组已完全填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662477/