-4

My first time posting here. I have small experience with Java and learning at the moment. So to the point. Description of program is: when user types "END" then the program should finish and save the input in a .txt file. My problem is I don't know how to add 'End'. for example I tried with 'while' loop but got errors, errors like my loop was infinite

while (mycontent != "END" || mycontent != "End") {
}

what is the best method and where in block should be? Thank you for your time

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Me {
public static void main(String[] args) {

   Scanner input = new Scanner(System.in);

   System.out.println("Please type your text and type 'END' to exit: ");

  BufferedWriter bw = null;

  try {

 String mycontent = input.nextLine();

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


  if (!file.exists()) {
     file.createNewFile();
  }


  FileWriter fw = new FileWriter(file);
  bw = new BufferedWriter(fw);
  bw.write(mycontent);
      System.out.println("File written Successfully");

} catch (IOException ioe) {
   ioe.printStackTrace();
} 

finally
{ 
   try{
      if(bw!=null)
     bw.close();
   }catch(Exception ex){
       System.out.println("Error in closing the BufferedWriter"+ex);
    }
}
}
}
ExDelta
  • 3
  • 2
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – SomeJavaGuy Jul 14 '15 at 14:04
  • `"I tried with 'while' loop but got errors"` - Reading the errors would be a *great* start in trying to resolve them. – David Jul 14 '15 at 14:05
  • User input isn't an exception. User typing "END" isn't an error, handling it is well defined in your assignment. – zubergu Jul 14 '15 at 14:05

1 Answers1

1

Please use .equals() method to check if the two strings have the same value.

while(myContent!=null && myContent.equals("END")) {
    // Do something
}

You can even use StringUtils function IsEmpty for the above checking, after importing org.apache.commons.lang.StringUtils library.

poorvank
  • 7,524
  • 19
  • 60
  • 102