在SPOJ上,如何在Java中的EOF之前读取此程序的输入? [英] How do I read input until EOF in Java for this program on SPOJ?
问题描述
问题网址: http://www.spoj.com/problems/PT07H/
顺便说一句,我试图通过3种不同的方法读取输入,但是没有成功,控制永远不会退出while()循环(即,它永远不会检测到EOF或EOS).
By the way, I tried to read an input by 3 different methods but no success, control never come out of while() loop (i.e., It never detects EOF or EOS).
这是我的代码,该代码读取输入的XML:
Here's my code that reads an input XML:
public static void main(String[] args) throws Exception {
// Input & Output
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
OutputStream out = new BufferedOutputStream(System.out);
int data;
char c;
String line;
StringBuilder xml = new StringBuilder();
// Read input
/*
// Method-1
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
line = in.nextLine();
for (int i = 0; i < line.length(); i++) {
c = line.charAt(i);
if (isValid(c)) {
xml.append(c);
}
}
}
// Method-2
while ((data = br.read()) != -1) {
c = (char) data;
if (isValid(c)) {
xml.append(c);
}
}
*/
// Method-3
while ((line = br.readLine()) != null) {
for (int i = 0; i < line.length(); i++) {
c = line.charAt(i);
if (isValid(c)) {
xml.append(c);
}
}
}
}
推荐答案
标准输入实际上 没有EOF,因此您将永远看不到它.当您从确实有结尾的实际文件(或其他流)中读取内容时,您的方法#3将起作用.
Standard input actually has no EOF, so you'll never see it. Your method #3 will work when reading from an actual file (or other stream) which does have an end.
(不确定,您可能想尝试在标准输入(Ctrl-D或Ctrl-Z)上键入" EOF,这可能行不通,不确定.)
(You may want to try to 'type' an EOF on the stdin (Ctrl-D or Ctrl-Z), which may or may not work, not sure.)
另请参见此问题.
这篇关于在SPOJ上,如何在Java中的EOF之前读取此程序的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!