【问题标题】:How to add an 'END' in my try and catch block?如何在我的 try and catch 块中添加“END”?
【发布时间】: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”不是错误,处理它在您的作业中已明确定义。

标签: java io


【解决方案1】:

请使用.equals()方法检查两个字符串是否具有相同的值。

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

您甚至可以在导入org.apache.commons.lang.StringUtils 库后使用StringUtils 函数IsEmpty 进行上述检查。

【讨论】:

  • 但是对于StringUtils,他需要apache commons lang
猜你喜欢
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多