执行.next()方法时关闭扫描仪对象? java的

时间:2013-01-21 16:00:34

标签: java sockets java.util.scanner

我有一个简单的问题,我正在制作一个在线游戏(在我移动到GUI之前了解基础知识)并且我有一些命令,例如,如果用户在控制台中输入'q',程序将终止(将但是如果错误发生在代码中的其他地方(即无法找到服务器),我会关闭所有连接/尝试连接。我还想关闭扫描仪对象,但扫描仪对象持有“.next()”方法。我尝试调用“.close()”和“.reset()”等,但没有任何东西会使扫描仪对象停止。如何停止扫描仪对象,以便完全关闭程序?

-Dan

public void commands(){
    char[] charArray;
    while(running){
        String input = scanCommands.next();
        if(input.length() > 1){
            command = 'x';
        }else{
            charArray = input.toCharArray();
            command = charArray[0];
        }
        switch(command){
            case 'h':
                System.out.println("Server Commands: ");
                System.out.println("Command:     Function:");
                System.out.println(" q        -   to exit the server.");
                System.out.println("done.");
                break;
            case 'q':
                System.out.println("Quiting...");
                quite();
                System.out.println("done.");
                return;
            default:
                System.out.println("Invalid server command");
                break;
        }
    }
}

//the quite method is the one that I call and should close everything, including the 
//scanner object.

public void quite(){
    running = false;
    try{
        IS.close();
        OS.close();
        send.close();
        recieve.close();
    }catch(Exception e){
        IS = null;
        OS = null;
        send = null;
        recieve = null;
    }
    String[] nullNames = new String[7];
    name.setArray(nullNames);
}

更新: 我习惯在相当方法中使用“.close()”,但它没有用。我再次尝试并进入调试模式模式,它只是保持“.close()”。一旦我输入“q”或其他任何内容,代码就会继续,并执行“.close()”。如何在不输入任何内容的情况下关闭它?

2 个答案:

答案 0 :(得分:0)

您没有关闭Scanner对象,因为它不在try-block中。

try{
    IS.close();
    OS.close();
    send.close();
    recieve.close();
}

应包括

scanCommands.close();

如果这会引发异常,请将其包含在您的问题中。

答案 1 :(得分:0)

作为一种快速解决方法,您可以在每次调用下一个方法之前尝试检查hasNext。