0

我编写了这个程序来从一个文件中获取学生的记录并将它们放入一个数组中。然后我对它们进行冒泡排序并尝试打印它们。

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中显示红色的“终止”图标(表明它仍在运行)。它也一直在吃我一半的资源。我该如何解决这个问题?

谢谢

4

2 回答 2

2

改变你循环到

while (fileIn.hasNext() && index < 15)

不需要for循环

想想 - 如果 index 小于 15 并且没有下一条记录会发生什么

于 2013-10-01T02:03:51.540 回答
0

index++位于while嵌套在循环内的for循环内。只有循环迭代至少 15 次,您的for循环才能退出。while

于 2013-10-01T02:06:19.997 回答