1
public class Diary {
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        PrintWriter output = null;
        try {
            output = new PrintWriter (new FileOutputStream("diaryLog"));
        } catch (FileNotFoundException e) {
             System.out.println("File not found");
             System.exit(0);
        }

        //Ok, I will ask the date for you here:
        System.out.println("Enter the date as three integers separated by spaces (i.e mm dd yyyy):");
        int month = input.nextInt();
        int day = input.nextInt();
        int year = input.nextInt();

        //And print it in the file
        output.println("Date: " + month +"/" + day + "/" + year);
        System.out.println("Begin your entry:");
        String entry= input.next();
        while("end".equals(entry))
        {
        output.print(entry + " ");
        }

        output.close();
        System.out.println("End of program.");
       }
 }

The goal of this program is to take input and create a diary entry and output the input to a file when the word end is inputed. When I compile the program does not terminate when I input end and my diary entry is not saved in the output file.

4 Answers 4

1

In your code the loop continues if the entry has value end. However you want the reverse of that so use ! operator. Also you did not re-assign the entry with a new value within loop, so if the first value for entry is itself end it will result into infinite loop.

You need to re-assign value to entry:

String entry;
while(!"end".equals(entry = input.next())) {// I had used `!` logical operator
    output.print(entry + " ");
}
Sign up to request clarification or add additional context in comments.

Comments

0

On each iteration of the loop, you want to task the user for more input. Because you want to ask the user to enter something at least once, you should use a do-while loop, for example...

String entry = null;
do {
    entry = input.nextLine();
} while (!"end".equals(entry));

Comments

0

There are couple of changes to be made. What you should have is:

 String entry= input.next();
    output.print(entry + " ");
    while(! "end".equals(entry))
    {

        entry= input.next();
    }

    output.close();
    System.out.println("End of program.");

The intension is, while the user doen't enter 'end' continue reading.

1 Comment

Also remember to close input: input.close();
0

The solution given above is correct but don't forget to close your input.Otherwise in eclipse you will face Heap Size issue when you will try to open your text file.

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.