Sam Wright
Sam Wright

Reputation: 13

How do I use a string conditional in a while loop, java?

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.

Upvotes: 1

Views: 3744

Answers (4)

arihant jain
arihant jain

Reputation: 43

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.

Upvotes: 0

user2575725
user2575725

Reputation:

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 + " ");
}

Upvotes: 1

Kedar Parikh
Kedar Parikh

Reputation: 1271

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.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347204

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

Upvotes: 0

Related Questions