So, I'm trying to have the user write a filename if they want to write to a file, and write "Thanks for playing" in the Console id they don't want to write to a file.
However, no matter if I type in "yes" or "no", it will either not give the file prompt, or goes into an infinite loop with the names and ages printed, depending on where I put it.
I'll post the code in question below.
String answer2;
String write;
String fileName;
ArrayList<String> names = new ArrayList<>();
ArrayList<String> ages = new ArrayList<>();
// If I put it here, it will do a infinite loop of the names and ages inputted.
// Prompt the user if they want to write to a file.
System.out.println("Do you want to write to a file? ");
answer2 = keyboard.nextLine();
do
{
// If I put it here, it will continue to ask me the question infinitely.
// Prompt the user if they want to write to a file.
// System.out.println("Do you want to write to a file? ");
//answer2 = keyboard.nextLine();
}
while (answer.equals("no"));
do
{
// Prompt for the filename
System.out.println("Enter your filename: ");
fileName = keyboard.nextLine();
//break;
//PrintWriter outputFile;
try
{
PrintWriter outputFile = new PrintWriter(fileName);
// Write the name(s) and age(s) to the file
outputFile.println(names);
outputFile.println(ages);
outputFile.close();
}
catch (FileNotFoundException e)
{
//
e.printStackTrace();
break;
}
}
while (answer2.equals("yes"));
do
{
System.out.println("Thanks for playing!");
break;
}
while (answer2.equals("no"));
keyboard.close();
A
do/whileloop does.. well, use a dictionary if you have to. It obviously loops. It keeps doing the thing in the brackets until the while clause is no longer true. Your code will continually keep asking.You want an
if, not ado/whileloop here.