【发布时间】:2015-06-29 12:05:56
【问题描述】:
第一次发帖! 我有一个作业到期,要求我编写一个 java 程序,从文本文件中读取数据并根据分数及其首字母对其进行排序。 文本文件如下:
John Doe 75
Joe Blow 65
Mary Smith 80
John Green 82
Jill White 97
这是我的代码:
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
String[] firstName = new String[5];
String[] lastName = new String[5];
int score[] = new int[5];
java.io.File file = new java.io.File("data.txt");
Scanner input = new Scanner(file);
int c=0;
while(input.hasNext()){
firstName[c] = input.next();
lastName[c] = input.next();
score[c] = input.nextInt();
c++;
}
input.close();
MichaelBubbleSort(score);
for(int x=4;x>=0;x--){
System.out.print(firstName[x].substring(0,1) + lastName[x].substring(0,1) + " " + score[x]);
System.out.println();
}
}
public static void MichaelBubbleSort(int[] arr){
int temp;
for(int i=0; i < arr.length-1; i++){
for(int j=1; j < arr.length-i; j++){
if(arr[j-1] > arr[j]){
temp=arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
但由于某种原因,它总是出现:
JW 97
JG 82
MS 80
JB 75
JD 65
输出应该是:
JW 97
JG 82
MS 80
JD 75
JB 65
有什么原因导致这种情况不断发生?
【问题讨论】:
-
您已经对分数进行了排序,但没有对名称进行相应的排序。这就是你面临这个问题的原因。
-
您希望得到哪种输出? (请编辑问题)
标签: java sorting bubble-sort