Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中EOFException的处理_Java_Exception_Exception Handling_Inputstream_Eof - Fatal编程技术网

java中EOFException的处理

java中EOFException的处理,java,exception,exception-handling,inputstream,eof,Java,Exception,Exception Handling,Inputstream,Eof,我有以下功能。我希望循环继续,直到消息等于“You have successfully loggin!”。但是当用户输入错误的输入(无效的用户名或密码)时,由于EOFEException,循环将无限继续。我怎样才能解决这个问题? 多谢各位 private void processConnection() throws IOException { boolean eofReached = false; String message; do

我有以下功能。我希望循环继续,直到消息等于“You have successfully loggin!”。但是当用户输入错误的输入(无效的用户名或密码)时,由于
EOFEException
,循环将无限继续。我怎样才能解决这个问题? 多谢各位

 private void processConnection() throws IOException
    {
        boolean eofReached = false;
        String message;
        do
        {
            try 
            {
                message = (String)input.readObject();
                if(message.equals("You have successfully logged in!"))
                {
                    displayMessage(String.format("\n%s ", message));
                    logged = true;
                    prepareUI();
                } 
                else
                {
                    displayMessage(String.format("\n%s %s", message, "\nTry again!") );
                }
            } 
            catch (ClassNotFoundException | EOFException  ex) 
            {
                  System.out.printf("\nend of registering");
                //  Logger.getLogger(ClientJFrame.class.getName()).log(Level.SEVERE, null, ex);
                  //eofReached = true;
            }        
             cout("registering");       
        } while(!logged && !eofReached);
    }

在您的代码示例中,您似乎拥有了所有需要的东西。只需取消注释您设置的
eofReached

行,我发现了我的错误。问题是服务器中没有这样的对应循环来响应所有请求。这就是我得到异常的原因。

这更多是一种风格选择,但是如果使用简单的while循环(循环以“while”开头)而不是do-while循环,代码将更易于阅读。您是否总是得到EOF错误?或者只是偶尔?你的“输入”是什么?你能用扫描仪把它包起来,然后做readLine()吗。在收到消息之前,它几乎会阻塞。因此,如果消息不等于“you have successfully loggin”,那么我总是会收到EOF异常。我不知道我是否可以用扫描仪来代替它。我正在响应服务器的应用程序的客户端中使用此函数。实际上,这是我的另一个问题,我什么时候应该选择ObjectInput/Output streams而不是Scanner和Formatter是的,但是如果eofReached等于true,那么如果我得到异常,我将退出循环,我将无法继续从输入中读取,但是如果你已经达到eof,那么就没有可以读取的输入了,所以你就完成了。