Question

I am writing a small little .jar application that asks user for a string and writes it into a .txt file. I am interested in the program keep executing the following instructions (that is, write date string, and write the input string into the text file) when the input string is not exit. My code does not work for that, ask it does not log the first line I input, nor the first exit I type. I tried a number of things, trying a do-while loop, but that didn't work. I wonder what the problem is?

try{
            String input = scanner();
            while(!input.equals("exit")){
                String fileLocation = "/Users/loop/Dropbox/goodTrance.txt";
                FileWriter writer = new FileWriter(fileLocation,true);

                writer.append(returnDate()+": ");
                writer.append(input + "\n");

                writer.flush();
                writer.close();
                input = scanner();
            }
        }catch(Exception e){
            e.printStackTrace();
        }

EDIT: scanner() is a static method that returns a scanner string. returnDate() returns today's date.

public static String returnDate(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();
        return dateFormat.format(date).toString();
    }

public static String scanner(){
        Scanner input = new Scanner(System.in);
        String writeSomething = input.nextLine();
        return writeSomething;
    }
Was it helpful?

Solution

What does a call to scanner() do? It looks like you're calling it twice each time you loop, and may be discarding the first call (but checking it) and storing the 2nd call and not checking it. Methinks you should call it only once for each loop.

Note, your code has other problems:

  • There's no need for the scanner() method.
  • There's no need to keep re-creating a Scanner object, and in fact by doing so and not releasing resources, you run the risk of running out of resources.
  • Instead create your Scanner object once, and use it inside of your try block, calling nextLine() on it as needed.
  • Also consider closing your file *after the while loop, and in fact in the finally block of your try block. Close your Scanner object there as well.
  • It's often a better idea to check your String with equalsIgnoreCase(...).
  • It's safer to check it like so:

String line = null;
while ("exit".equalsIgnoreCase(line)) {
  line = scanner.nextLine();
  // etc...

To avoid NPE

OTHER TIPS

Do you have a terminal connection which is sending the text? If that's the case the terminal protocol sends character by character which means you will not ever get the scanner().equals("exit") to true since it only takes one character and not a whole String.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top