我正在尝试创建一个程序,每次用户按下“c”时重新打印文本文件simple.txt
,但是使用我的代码,它只会打印一次:
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
Scanner fileSearch = new Scanner(new File("simple.txt"));
UI(console, fileSearch);
}
public static void UI (Scanner console, Scanner fileSearch) {
String choice = "Start";
while (!choice.equals("q")) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
choice = console.next();
choice = choice.toLowerCase();
if (choice.equals("c")) {
System.out.println("Create");
CreateMadLibs(fileSearch);
} else if (!choice.equals("q")) {
System.out.println("I don't understand.");
}
}
}
public static File FileGrab (Scanner fileSearch) {
File thing = new File(fileSearch.next());
while (fileSearch.hasNextLine()){
System.out.println(fileSearch.nextLine());
}
return thing;
}
public static void CreateMadLibs (Scanner fileSearch) {
FileGrab(fileSearch);
}
我认为问题是我在main中创建了扫描程序fileSearch
而不是UI
。我尝试在fileSearch
语句中初始化if
,但这给了我一个fileNotFoundException。就是这样,我明白了:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at test.FileGrab(test.java:28)
at test.CreateMadLibs(test.java:36)
at test.UI(test.java:20)
at test.main(test.java:9)
答案 0 :(得分:1)
您可以将fileSearch
放入while
循环,以便每次重新搜索循环时找到file
。您只需在UI(console);
中致电main
。
此外,我建议最后关闭scanner
,因为它可能不会再次使用(除非当然重新输入c
)。
public static void UI(Scanner console) throws FileNotFoundException {
String choice = "Start";
while (!choice.equals("q")) {
Scanner fileSearch = new Scanner(new File("simple.txt"));
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
choice = console.next();
choice = choice.toLowerCase();
if (choice.equals("c")) {
System.out.println("Create");
CreateMadLibs(fileSearch);
} else if (!choice.equals("q")) {
System.out.println("I don't understand.");
}
fileSearch.close();
}
}
答案 1 :(得分:1)
您的代码中有一些功能上无效的行,我建议通过执行以下操作来修改FileGrab
方法:
public static void /*File*/ FileGrab ( Scanner fileSearch ) {
//File thing = new File(fileSearch.next()); // this line is useless
while (fileSearch.hasNextLine()){
System.out.println(fileSearch.nextLine());
}
//return thing; // this either
}