我写了这个程序,从文件中记录学生的记录并将它们放入一个数组中。然后我冒泡它们并尝试打印它们。
import java.io.*;
import java.util.Scanner;
public class StudentTest
{
public static void main(String[] args)
{
String name;
String address;
String major;
double gpa;
int classLevel;
int college;
String idNumber;
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("student.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
Student[] aStudent = new Student[15];
int index = 0;
for (index=0; index < 15;)
{
while (fileIn.hasNext())
{
name = fileIn.nextLine();
address = fileIn.nextLine();
major = fileIn.nextLine();
gpa = fileIn.nextDouble();
classLevel = fileIn.nextInt();
college = fileIn.nextInt();
fileIn.nextLine();
idNumber = fileIn.nextLine();
aStudent[index] = new Student(name, address, major, gpa, classLevel, college, idNumber);
aStudent[index].Display();
System.out.println(index);
index++;
}
}
Student temp= null;
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[c].getName().compareTo(aStudent[c+1].getName()) > 0)
{
temp = aStudent[c];
aStudent[c]=aStudent[+1];
aStudent[+1]=temp;
}
}
}
for (int d = 0; d < aStudent.length; d++)
{
aStudent[d].Display();
System.out.println();
//aStudent[d].Display();
}
//System.out.println(aStudent);
}
}
控制台将在加载数组时显示未排序列表的第一个打印,然后只是坐在那里。我让它走了十分钟,它仍然在eclipse中显示红色的“终止”图标(表示它仍然在运行)。它一直在吃掉我一半的资源。我该如何解决这个问题?
感谢
答案 0 :(得分:2)
将循环更改为
while (fileIn.hasNext() && index < 15)
不需要循环
想想 - 如果索引小于15并且没有下一条记录
会发生什么答案 1 :(得分:0)
index++
位于嵌套在while
循环中的for
循环内。只有for
循环至少重复15次才会退出while
循环。