gpt4 book ai didi

java - 程序占用了我的所有资源并且未完成(可能是无限循环?)

转载 作者:行者123 更新时间:2023-12-02 06:41:19 24 4
gpt4 key购买 nike

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

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

谢谢

最佳答案

将循环更改为

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

不需要for循环

思考 - 如果索引小于 15 并且没有下一条记录会发生什么

关于java - 程序占用了我的所有资源并且未完成(可能是无限循环?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com