任务是组织和显示与标记对应的用户输入.
例如,
姓名:奥斯卡马克:25,姓名:鲁宾马克:45,姓名:杰克马克:13
所以应该显示:
Rubin 45
Oscar 25
Jake 13
Run Code Online (Sandbox Code Playgroud)
当前代码仅显示名称和标记,但不按排列顺序显示.我怀疑它可能与做int
和String
,但我不能完全肯定.
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i < 5; i++) {
ArrNames[i] = JOptionPane.showInputDialog("Enter a Name:");
ArrMarks[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter a mark:"));
}
}
private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i < 5 - 1; i++) {
for (int j = i +1; j < 5; j++) {
if (ArrNames[i].compareTo(ArrNames[j]); //>0 sorts in ascending order <0 sorts in descending order ==0 tests for duplicate string value
//using .compareTo because checking 2 names
{
//sorting the names
String temp = ArrNames[i];
ArrNames[i] = ArrNames[j];
ArrNames[j] = temp;
//sorting the marks
int temp1 = ArrMarks[i];
ArrMarks[i] = ArrMarks[j];
ArrMarks[j] = temp1;
}
}
}
}
private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i < 5; i++) {
txaDisplay.append(ArrNames[i] + "\t\t" + ArrMarks[i] + "\n");
}
}
Run Code Online (Sandbox Code Playgroud)
该问题的正确解决方案是更换
if (ArrNames[i].compareTo(ArrNames[j]))
Run Code Online (Sandbox Code Playgroud)
同
if (ArrMarks[i] < ArrMarks[j])
Run Code Online (Sandbox Code Playgroud)
我最初是在比较名称,而不是Marks的实际整数值.