3

I need to do the following exercise: a) Make a new text file b) Put the user's input into that text file c) we must save all user's input while user keeps typing but as soon as user pressing Enter in a new line (When an empty string is sent) the user must get out of the program. For coding this issue I have write the following codes, but when I try it by myself so I am stuck at while loop, cant get out when I sending empty string. So could anyone help with a solution for this issue?

Thanks

I have tried some of the solutions I have found on youtube like making if statement inside the while loop or adding the code that takes the input of the user inside the loop's condition. So I do not know what to do at the next stage. I tried to see the console window via the Eclipse output.


import java.io.*;
import java.util.Scanner;
public class lesson {
    public static void main(String[] args) throws IOException {

        File file = new File("mytext.txt");

        if (file.exists() == false) {
            file.createNewFile();
        }
        PrintWriter pw = new PrintWriter(file);
        System.out.println("Enter a text here: ");
        String str;
         while (true) {
             Scanner input = new Scanner(System.in);
            str = input.next();
            pw.println();
            if (str.equals(null)) {
                break;
            }
        } 
        pw.close();
        System.out.println("Done");
    } 
}

The user must get out of the loop when he/she sends an empty string. and the writing to the file must be finished.

  • Possible duplicate of [How to exit loop with ENTER](https://stackoverflow.com/questions/21698038/how-to-exit-loop-with-enter) – Mebin Joe Apr 04 '19 at 11:23
  • check your string as -> str == null to break the loop – Onkar Musale Apr 04 '19 at 11:27
  • @OnkarMusale, I tried but it did not work, it still keeps going to new lines. but one user suggested me using exit to break the loop instead of sending empty string, it worked well. But now I have a new problem and that's nothing is saved in the text file. :/ – Habiballah Hezarehee Apr 04 '19 at 11:37
  • 1
    Do you know how to debug your code? If you are using an IDE, like [Eclipse](https://www.eclipse.org), then it will have a debugger. In order to become a proficient programmer, you need to learn how to debug your code. Regardless, in the code you posted, in order to quit the loop, the `if` condition needs to be true. In other words `str.equals(null)` needs to return true, but you say it never exits the loop so `str` must never be null, right? Also, you should create your `Scanner` **before** the `while` loop. – Abra Apr 04 '19 at 11:44
  • @HabiballahHezarehee what is new problem ? – Onkar Musale Apr 04 '19 at 11:45
  • @Abra I have did as you said, moved the Scanner declaration outside the loop, and then tried the condition str == null or str == "" but both have same result. Unfortunately, it does not break the loop. – Habiballah Hezarehee Apr 04 '19 at 13:10
  • I already wrote that `str` is never null. That is obvious from your original post and code. Hence `str == null` is the same as `str.equals(null)`. Also `str == ""` is not the correct way to test for an empty `String`. Do you know the difference between the logic operator `==` and the method `equals()`? I still think you need to learn how to debug your code. Have you tried to debug it? – Abra Apr 04 '19 at 13:36
  • @Abra actually I did debugging, but I do not know how to find the solution :/, do you know how I can fixt it? – Habiballah Hezarehee Apr 04 '19 at 14:07
  • @Joe at the link "How to exit loop with ENTER" you give, there is no valid solution – Jaja Apr 04 '19 at 16:05

2 Answers2

1

To achieve this, we check is length of input is >0:

import java.io.*;
import java.util.Scanner;
public class lesson {
    public static void main(String[] args) throws IOException {

        File file = new File("mytext.txt");

        if (file.exists() == false) {
            file.createNewFile();
        }
        PrintWriter pw = new PrintWriter(file);
        System.out.println("Enter a text here: ");
        String str;
        Scanner input = new Scanner(System.in);
        while ((str = input.nextLine()).length() > 0) {
             //str = input.next();
             pw.println(str);
        } 
        pw.close();
        System.out.println("Done");
    } 
}
Jaja
  • 662
  • 7
  • 15
1

First the code, then the explanation...

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Lesson {
    public static void main(String[] args) {
        File file = new File("mytext.txt");
        try (Scanner input = new Scanner(System.in);
             PrintWriter pw = new PrintWriter(file)) {
            System.out.println("Enter a text here: ");
            String str = input.nextLine();
            while (str.length() > 0) {
                pw.println(str);
                pw.flush();
                str = input.nextLine();
            }
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
        System.out.println("Done");
    }
}

The above code requires at least Java 7 since it uses try-with-resources. Scanner should be closed, just like PrintWriter should be closed. The try-with-resources ensures that they are closed. Note that if file mytext.txt doesn't exist, creating a new PrintWriter will also create the file and if the file already exists, its contents will be removed and replaced with the text that you enter.

After that the prompt is displayed, i.e. Enter a text here, and the user enters a line of text. Method nextLine() will get all the text entered until the user presses Enter. I read your question again and the program should exit when the user presses Enter without typing any text. When the user does this, str is an empty string, i.e. it has zero length. That means I need to assign a value to str before the while loop, hence the first call to method nextLine() before the while loop.

Inside the while loop I write the value entered by the user to the file mytext.txt and then wait for the user to enter another line of text. If the user presses Enter without typing any text, str will have zero length and the while loop will exit.

Written and tested using JDK 12 on Windows 10 using Eclipse for Java Developers, version 2019-03.

Abra
  • 19,142
  • 7
  • 29
  • 41