I'm trying to make a program which reprints the text file simple.txt
every time the user presses "c", but with my code, it will only print once:
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);
}
I think the issue is that I create the scanner fileSearch
in main instead of in UI
. I tried initializing fileSearch
in the if
statement, but that gave me a fileNotFoundException. As is, I get this:
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)
You can put the fileSearch
into the while
loop so that it finds the file
each time you re-search through the loop. You just call UI(console);
in the main
then.
Also, I would recommend closing the scanner
at the end, as it may not be used again (unless of course c
is re-entered).
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();
}
}
You have some lines in your code that functionally do nothing, I suggest to modify the FileGrab
method by doing something like this :
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.