我正在编写一个从文本文件读取输入的程序,当它到达文件末尾时,我应该从控制台获取输入。我编写了代码,但它似乎无法正常工作。有人有什么建议吗?
public static void main(String args[]) {
PQHeap newsFeed = new PQHeap();
if (args.length < 2) {
System.out.println("Usage: java NewsFeed inputFile commandFile");
}
if (args.length == 2) {
try {
BufferedReader input = new BufferedReader(new FileReader(
args[0]));
String line;
while ((line = input.readLine()) != null) {
String[] tokens = line.split(",");
int like = Integer.parseInt(tokens[1]);
int age = Integer.parseInt(tokens[2]);
newsFeed.insert(tokens[0], like, age);
}
BufferedReader command = new BufferedReader(new FileReader(
args[1]));
BufferedReader commIn = new BufferedReader(
new InputStreamReader(System.in));
boolean done = false;
String Input = null;
while (!done) {
Input = null;
System.out.println("Enter a command - a, i, l, p or q: ");
if ((Input = command.readLine()) == null) {
Input = commIn.readLine();
}
if (Input.length() > 0) {
char choice = Input.charAt(0); // strip off option
// character
String remainder = ""; // used to hold the remainder of
// input
// trim off any leading or trailing spaces
remainder = Input.substring(1).trim();
switch (choice) {
case 'a':
newsFeed.insert(remainder, 0, 1);
break;
case 'i':
newsFeed.incrementDay();
break;
case 'l':
String[] tokens = remainder.split(",");
int id = Integer.parseInt(tokens[0]);
int likes = Integer.parseInt(tokens[1]);
newsFeed.increaseLikes(id, likes);
break;
case 'p':
if (remainder.length() == 0) {
newsFeed.displayTop(System.out, newsFeed.size());
} else {
newsFeed.displayTop(System.out,
Integer.parseInt(remainder));
}
break;
case 'q':
// exit if user input 'x'
done = true;
break;
default:
System.out.println("Unknown Command");
break;
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Cannot find the specified file");
System.exit(0);
} catch (IOException e) {
System.out.println("Error: an input error has occured");
System.exit(0);
}
}
}
但是在我到达文件末尾后,它并没有立即从控制台获取输入。这是到达文件末尾后的输出
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q:
Enter a command - a, i, l, p or q: