【发布时间】:2015-07-14 14:02:52
【问题描述】:
我第一次在这里发帖。我目前在 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);
}
}
}
}
【问题讨论】:
-
"I tried with 'while' loop but got errors"- 阅读错误将是一个伟大的开始尝试解决它们。 -
用户输入也不例外。用户键入“END”不是错误,处理它在您的作业中已明确定义。