为什么扫描仪在第一次迭代后找不到线?



我正在编写一个程序,它基本上充当电子邮件客户端,作为Java课程家庭作业的一部分。我通常不会求助于互联网来回答我的问题,但这超出了教授试图让我们学习/练习的内容,我需要找到一种方法来解决这个问题。

问题:如果我运行程序,并输入第二个命令(ri),它将提示我输入数字,然后通过显示消息完成,但紧接着,当它返回到.run()方法的第二次迭代时,控制台返回:

Exception in thread "main" java.util.NoSuchElementException: No Line Found
at java.util.scanner.nextLine(Unknown Source)

这是代码(我只包含重要的东西...或者至少我认为重要)。

public class CmdLoop {
private MailClient _client;
Scanner kbd;
private Hashtable<String, ICommand> _commands = new Hashtable<String, ICommand>();
public CmdLoop(MailClient client) {
_client = client;
_commands.put("h", new client.cmd.Help());
_commands.put("ri", new client.cmd.ReadInbox());
kbd = new Scanner(System.in);
}
public void run2() {
System.out.print("nMail: ");
String command = kbd.nextLine();
ICommand call = _commands.get(command);
if (command.equals("q"))
return;
else if (call == null)
System.out.println(command + " not understood, type h for help");
else if (call.equals(""))
System.out.println(command + " not understood, type h for help");
else call.run(_client);
this.run2();
}

和 ri 类:

public class ReadInbox implements ICommand {
@Override
public void run(MailClient client) {
Scanner sc = new Scanner(System.in);
MailBox in = client.getInbox();
if(in.count() < 1)
System.out.println("Inbox empty");
else {
System.out.print("Enter the number of the message you would like to read: ");
int n = Integer.parseInt(sc.nextLine());
if(n > in.count())
System.out.println("Message number " + n + " can't be found");
else
in.getMessage(n - 1).show();
}
sc.close();
}
}

基本上,它到达 ReadInbox.run() 调用的末尾,然后调用 this.run2(),返回顶部,输出"Mail:",然后返回错误。这是我测试中的控制台外观:

Mail: ri
Enter the number of the message you would like to read: 1
Date: 2015/04/29 20:24:17
From: Charles Barkley (Charlie) <Charles@gmail.com>
Subj: testerino
this is another test

Mail: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at client.CmdLoop.run2(CmdLoop.java:28)
at client.CmdLoop.run2(CmdLoop.java:37)
at Main.main(Main.java:29)

如果我是对的,让他们都在同一台扫描仪上运行它会解决我的问题,我觉得我应该知道如何做到这一点,但我画了一个空白。还有别的办法吗?

根据文档,Scanner将"如果未找到行",则会引发该异常。您可以通过首先调用kbd.hasNextLine()来防止这种情况,它会告诉您是否有东西可以得到。只要扫描仪未关闭,就会等待输入一行。

run2方法中尝试此操作:

String command = null;
if (kbd.hasNextLine())
command = kbd.nextLine();
ICommand call = _commands.get(command);

我找到了答案。我摆脱了 sc.close();在 ReadInbox 类中。我不知道为什么这有效,但它确实如此。如果有人能提供解释,非常感谢,否则,无论如何,至少它有效。

相关内容

最新更新