Reputation: 4845
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;
}
Upvotes: 2
Views: 1520
Reputation: 1
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.
Upvotes: 0
Reputation: 285405
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:
scanner()
method. nextLine()
on it as needed.equalsIgnoreCase(...)
.String line = null;
while ("exit".equalsIgnoreCase(line)) {
line = scanner.nextLine();
// etc...
To avoid NPE
Upvotes: 2