我是一名新编码员,我的班级最近开始学习数组。我整天都在为这一项计划任务而苦恼。它不会在几天内到期,但我对此感到非常沮丧。
我们必须打印出一份测试分数列表以及与之相关的相关ID。我们必须从最高到最低排序测试分数,但不修改数组 - 所以没有数组排序,或任何类似。 “建议的解决方案”说:
找出最高分,跟踪其下标。
打印此分数以及相应的ID。
将该分数设置为相反(这使得它最小 得分!)。
重复步骤1-3,直到处理完所有21个分数。
停止并打印相应的消息。
我一直在努力遵守这些指示,因为本周余下的其他程序将依赖于此。然而,我的方法是有缺陷的,因为我的代码打印出最大分数为110,238次迭代的238。 我在使用这段代码时遇到了很大麻烦,这真让我感到沮丧。这就是我到目前为止所做的:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Prog408a {
static Scanner inFile = null;
static Scanner inFile2 = null;
public static void main (String[]args) {
try {
// create scanner to read file
inFile = new Scanner(new File ("prog408a.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
int [] ids = new int[26];
int [] scores = new int[26];
int first = 0;
int second = 0;
int counter = 0;
int max, maxid, supermax;
do {
ids [first] = inFile.nextInt();
scores [second] = inFile.nextInt();
first++;
second++;
} while (inFile.hasNextInt());
/* initial values of max, maxid */
System.out.println("ID\t\tScore");
maxid = ids[0];
supermax = scores[0];
max = scores[0];
int index=0;
while (counter < scores.length) {
for (int x = 0; x < scores.length - 1; x++) { // scroll through the indexes.
if (scores[x] > max) {
max = scores[x];
index = x; // keep the index of the biggest number.
}
max = -1 * (scores[index]);
}
System.out.println("The maximum score is " + ids[index] + ", " + scores[index]);
counter++;
}
}
}
这是数据文件中的内容。
365 265
222 223
306 262
003 559
004 560
203 224
113 243
208 242
213 229
115 257
302 242
223 230
001 599
311 256
323 245
321 245
123 253
104 239
002 513
112 239
207 228
325 246
116 246
218 243
110 238
如果帖子中有任何格式错误,请原谅。
答案 0 :(得分:2)
__weak
输出:
while (counter < scores.length - 1) {
for (int x = 0; x < scores.length - 1; x++) { // scroll through the indexes.
if (scores[x] > max) {
max = scores[x];
index = x; // keep the index of the biggest number.
}
}
System.out.println("The maximum score is " + ids[index] + ", " + scores[index]);
max = -1 * (scores[index]);
scores[index] = -1 * (scores[index]); // change the value in the original array so it won't find the same max again
counter++;
}
你可能想要添加一个小函数,在开始时用ID Score
The maximum score is 1, 599
The maximum score is 4, 560
The maximum score is 3, 559
The maximum score is 2, 513
The maximum score is 365, 265
The maximum score is 306, 262
The maximum score is 115, 257
The maximum score is 311, 256
The maximum score is 123, 253
The maximum score is 325, 246
The maximum score is 116, 246
The maximum score is 323, 245
The maximum score is 321, 245
The maximum score is 113, 243
The maximum score is 218, 243
The maximum score is 208, 242
The maximum score is 302, 242
The maximum score is 104, 239
The maximum score is 112, 239
The maximum score is 110, 238
The maximum score is 223, 230
The maximum score is 213, 229
The maximum score is 207, 228
The maximum score is 203, 224
The maximum score is 222, 223
打印额外的零。