我第一次在这里发帖。目前我对Java和学习都没有什么经验。言归正传。程序描述为:当用户输入"END"时,程序将结束并将输入保存为。txt文件。我的问题是我不知道如何添加"结束"。例如,我尝试使用'while'循环但得到错误,错误就像我的循环是无限的
while (mycontent != "END" || mycontent != "End") {
}
最好的方法是什么,在块应该在哪里?谢谢你的宝贵时间
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);
}
}
}
}
请使用.equals()
方法检查两个字符串的值是否相同
while(myContent!=null && myContent.equals("END")) {
// Do something
}
在导入org.apache.commons.lang.StringUtils
库后,甚至可以使用StringUtils
函数IsEmpty
进行上述检查。