我正在尝试从命令行读取用户的输入。对于 filename
的输入,程序应该在检测到用户提交了空白值时退出。
但是,无论用户输入是否包含任何内容,程序总是会转到“内部读取文件”代码。它永远不会执行“程序将立即退出”代码。我尝试了不同的编码方式,所有方式都得到了相同的结果。有什么问题吗?
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
while (true){
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null) {
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
System.exit(0);
}
}
最佳答案
使用 (filename = br.readLine()) !=null
添加一个额外的条件 filename.trim().length()>0
。因为 != null
不会检查空格。以及为什么你把 while(true).根据您当前的代码,它是无用的。
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String collection;
String filename;
System.out.println("Enter the collection name: ");
collection = br.readLine();
String urlString = "http://localhost:8983/solr/" + collection;
solr = new HttpSolrClient(urlString);
doc1 = new SolrInputDocument ();
System.out.println("Enter the file name: ");
while ((filename = br.readLine()) !=null && filename.trim().length()>0){
System.out.println("Inside reading file ");
parseUsingStringTokenizer(filename);
System.out.println("Enter the file name: ");
}
System.out.println("Program will exit now...");
}
关于java - 在命令提示符输入中从 BufferedReader 读取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762122/