Trying to get filename by user input, and print message if the say "no" to wanting to write to a file

109 Views Asked by At

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();
1

There are 1 best solutions below

4
rzwitserloot On

A do / while loop 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 a do/while loop here.