I'm having an issue with my code, where the loop works fine if a file exists, but if it doesn't then it only repeats once. I'd like it to work so that if a user enters a filename, and that file exists, it outputs that files content, and then asks the name of a new file. It should keep doing this until the user enters an escape word. If the file doesn't exist, it should tell them the file doesn't exist, and then prompt them to enter a new file name to see if it exists. This should loop continuously until the escape word is entered. Once the escape word is entered, it should output the end game message.
I need to accomplish this without using methods, since it's for a college beginning java class. I have only a few weeks of coding experience and I'm completely stuck on getting this to function properly. My teacher suggested to "use an if else block to make the 2 paths mutually exclusive," although I'm not quite sure what this means or how to accomplish it.
Can anyone help me fix my code to accomplish the above?
Relevant code:
while (!filename.equals(escapeWord))
{
System.out.print("\nWhere would you like to go?\n");
filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
if (!file.exists())
{
System.out.println("You can't go that way!");
return;
}
while (inputFile.hasNext())
{
String fileRead = inputFile.nextLine();
System.out.println(fileRead);
dayCount += 1;
}
inputFile.close();
}
//End Game Message
System.out.println("Congratulations, your adventure is over. " +
"You spent " +dayCount + " days adventuring!");