我正在创建一个程序,该程序读取名称和年龄的文件,然后按升序打印出来。我正在解析该文件以找出名称年龄对的数量,然后将数组变大。 输入文件如下所示: (23,Matt)(2000,杰克)(50,Sal)(47,Mark)(23,Will)(83200,Andrew)(23,Lee)(47,Andy)(47,Sam)(150,Dayton)
当我运行我的代码时,我得到(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;
}
}
}
}
}
输出示例 要读取的文件: file.txt (0,无) 流程结束,退出代码为0
答案 0 :(得分:0)
您的代码要做的是扫描文件两次。 在第一个循环中,您要做
String data1 = inputFile.nextLine();
代码读取第一行,然后扫描程序转到下一行(第二行)。 稍后,您再次执行inputFile.nextLine();。第二行为空,代码永远不会进入第二个循环,也永远不会读取内容。
如果可以使用列表,则应创建两个数组列表,并在第一次扫描中将年龄和名称添加到数组列表中,因此您只需扫描一次文件。完成后,您可以将阵列从arraylist中移出。
如果您只应使用数组并且要进行简单的更新,只需在第二个循环之前添加另一个扫描器即可:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line