输入要处理的文件后,命令行跳转到下一行但保持空白,而不是打印所需的数组。我想调用getInputScanner()方法来生成访问该文件的扫描程序,在用户输入文件后,命令行跳转到下一行,而不是处理任何文本。有什么想法吗?
import java.util.*;
import java.awt.*;
import java.io.*;
public class Test {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
Scanner input = getInputScanner(console);
System.out.println("{" + nameArr(input) + "}");
}
public static Scanner getInputScanner(Scanner console) {
System.out.print("Please enter a file to process: ");
File file = new File(console.next());
while (!file.exists()) {
System.out.print("\nFile does not exists.\nPlease enter a new file name: ");
file = new File(console.next());
}
try {
Scanner fileScanner = new Scanner(file);
return fileScanner;
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return null;
}
public static String [] nameArr(Scanner input) {
int count = 0;
while (input.hasNextLine()) {
count++;
}
String [] nameArray = new String[count];
while (input.hasNextLine()) {
String line = input.nextLine();
for (int i = 0; i < nameArray.length; i++) {
nameArray[i] = lineProcess(input.nextLine());
}
}
return nameArray;
}
public static String lineProcess(String line) {
Scanner lineScan = new Scanner(line);
String line2 = lineScan.nextLine();
String lineString[] = line2.split(" ");
String name = lineString[0];
return name;
}
}
答案 0 :(得分:0)
您已经无限loop
因为您没有推进扫描程序调用{{1}}:
input.nextLine()
我看到代码的其他部分我错了,尝试使用while (input.hasNextLine()) {
count++;
}
代替java.util.List
来收集处理文件行中的array
:
names