我正在创建一个程序,该程序读取姓名和年龄的文件,然后按升序打印它们。我正在解析文件以找出姓名年龄对的数量,然后使我的数组变得那么大。 输入文件如下所示: (23,马特)(2000, jack )(50,萨尔)(47,马克)(23,威尔)(83200,安德鲁)(23,李)(47,安迪)(47,萨姆)(150,代顿)
当我运行代码时,我得到 (0,null) 的输出,但我不确定为什么。我已经尝试修复它有一段时间了,但迷失了。如果有人可以提供帮助,那就太好了我的代码如下。
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
输出示例 要读取的文件: 文件.txt (0,空) 进程已完成,退出代码为 0
最佳答案
您的代码的作用是扫描文件两次。 在第一个循环中,您执行
String data1 = inputFile.nextLine();
代码读取第一行,然后扫描仪转到下(第二)行。 稍后你再次执行 inputFile.nextLine();第二行是空的,代码永远不会进入第二个循环,并且内容永远不会被读取。
如果您可以使用列表,则应创建两个数组列表,并在第一次扫描时将年龄和姓名添加到数组列表中,以便扫描一次文件。完成后,您可以从数组列表中获取数组。
如果您应该只使用数组并且想要一个简单的更新,只需在第二个循环之前添加另一个 Scanner 即可:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line
关于java - 当我运行代码时,我得到 (0, null) 并且无法弄清楚为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58230183/