Java 使用扫描仪重复文件打印
我正在尝试制作一个程序,每次用户按“c”时都会重新打印文本文件Java 使用扫描仪重复文件打印,java,intellij-idea,io,java.util.scanner,Java,Intellij Idea,Io,Java.util.scanner,我正在尝试制作一个程序,每次用户按“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, f
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中创建了scannerfileSearch
,而不是在UI
中。我尝试在if
语句中初始化fileSearch
,但这给了我一个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)
您可以将
fileSearch
放入while
循环中,以便每次重新搜索循环时它都会找到文件。您只需调用UI(控制台)然后,在main
中选择code>
此外,我建议在最后关闭扫描仪
,因为它可能不会再次使用(当然,除非重新输入c
)
您的代码中有一些行在功能上不起任何作用,我建议通过如下操作修改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
}
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
}