1

I am trying to write a program that asks the user to pu in the name of a limerick they would like to save, then it creates a file with the name of that limerick and then asks them to write the limerick, which will then be saved to file. I have this code to creae the file, ut when i try to write the limerick to the file it seems to get caught in a loop and continualy wite the first line entered to the file. Any help would be very much appreciated?

public void start () {
    System.out.println("<<THIS PROGRAM SAVES A LIMERICK THAT YOU HAVE WROTE>>");
}    

public File create () {
    System.out.println("<<ENTER THE NAME OF THE LIMERICK>>");
    name = scan.nextLine();
    nameFile = name + ".txt";
    File file = new File(nameFile);
    try {
        if (file.createNewFile() ) {
            System.out.println("<<FILE CREATED>>");
        } else {
            System.out.println("<<FILE ALREADY EXISTS>>");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}

public void write () {
    Limerick write = new Limerick();
    File file = write.create();
    System.out.println("<<ENTER THE LIMIRICK>>");
    PrintWriter pw;
    try {
        pw = new PrintWriter (new BufferedWriter (new FileWriter(file)));
        limerick = scan.nextLine();
        while (!(limerick.equals("DONE"))) {
            pw.println(limerick);
        }
        pw.close();
        System.out.println("<<LIMERICK WRITTEN TO FILE>>");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

public static void main (String args[]) {       
    Limerick method = new Limerick();
    method.start();
    method.write();

}
1
  • The value of limerick should change inside the while (!(limerick.equals("DONE"))) loop, or it will be an infinite loop (e.g put limerick = scan.nextLine(); inside the loop). Commented Dec 5, 2018 at 13:08

2 Answers 2

2

In the following loop the value of limerick is never updated and hence it goes into an infinite loop

while (!(limerick.equals("DONE"))) {
    pw.println(limerick);
}

Change it to something like this :

while (!(limerick.equals("DONE"))) {
    pw.println(limerick);
    limerick = scan.nextLine();
}

Thereby after each iteration the value of limerick is updated.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to run scan.nextLine() inside the loop:

    while (!((limerick = scan.nextLine()).equals("DONE"))) {
        pw.println(limerick);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.