嗨我正在玩游戏,直到用户在命令行中退出。
用户可以输入不同的命令,比如get and go,使用get命令,用户可以说出了什么,得到棒球棒。我在我的代码中做的是拆分命令。 一切正常,但我发现了一个我无法解决的错误。如果我输入get并按 space 然后 ctrl z 它会进入一个永远不会结束的while循环。 它只发生在 ctrl z (1次用 ctrl c 但在那之后不再有了1次)
我知道它的代码很重要,但我非常感谢任何帮助 我的代码
private void run()
{
while (! quitCommand)
{
String input = null;
try
{
input = null;
System.out.println("Input "+ input);
System.out.println("Give a command.");
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
input = is.readLine();
handleCommand(input);
// As long as the command isn’t to quit:
// get the next input line and handle it. (With handleCommand.)
}
catch (Exception e)
{
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
/**
* @param userInput (This is the entire input string from the user.)
*
* (Tell others to) Perform the task which belongs to the given
* command.
*/
private void handleCommand(String userInput)
{
// Split the user input string.
if (userInput != null) // user input can not be empty
{
String[] delenTekst = userInput.split(" ");
// The first word is a command. The rest is extra information
String command = delenTekst[0];
String extra = "";
for (int i = 1; i < delenTekst.length; i ++)
{
if (i == 1)
{
extra = extra + delenTekst[i];
}
else
{
extra = extra +" " + delenTekst[i];
}
}
switch (command)
{
// Check if the command is to travel between rooms. If so, handle
case "go"
:
this.checkRoomTravel(extra);
break;
// If there isn’t any room travel, then check all other command
case "get"
:
System.out.println("Looking for " +extra );
this.handleGetCommand(extra);
break;
case "quit"
:
quitCommand = true;
break;
default
:
System.out.println("Command is not known try help for information");
break;
}
}
else
{
userInput = "help";
}
}
我是java的新手,所以它可以是非常简单的东西。
在我的脚本顶部我有一个私有布尔quitCommand = false;这是检查用户是否输入了退出
答案 0 :(得分:1)
Ctrl + Z 关闭控制台,因此您的readLine()
返回null,假装表示已到达文件末尾。因此,您需要做的就是检查null
返回的readLine()
,并在处理“退出”时处理此问题。
我已经改变了你的代码(只是为了测试我的论文)并且还提供了一些内容,例如:每次读一行时都不需要重新创建BufferedReader
。
private boolean quitCommand = false;
private void runIt() {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while(!quitCommand) {
try {
System.out.print("Give a command: ");
input = is.readLine();
// As long as the command isn’t to quit:
if(input == null || "quit".equals(input.trim())) quitCommand = true;
if(quitCommand) break;
// get the next input line and handle it. (With handleCommand.)
String[] words = input.trim().split("\\s+");
// ** This is the original handleCommand line **
System.out.println(input + ":" + Arrays.toString(words));
}
catch (Exception e) {
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
顺便说一句:要将输入分成单词,我会使用正则表达式,如我的代码所示。如果用户输入制表符或多个空格,这也适用。
答案 1 :(得分:0)
在DOS / Windows Ctrl + Z 表示输入结束。这会导致readLine()返回null
,无论您调用它多少次。这可能会导致您的代码失败,因为您似乎没有检查它。我怀疑你得到一个NullPointerException,你假装没有发生,并且无休止地再次尝试。