0

I have the following function. I want the loop to continue until the message equals "You have successfully logged in!". But when the user enters a wrong input (invalid username or password) then the loop goes on infinitely, because of an EOFException. How can I solve this? Thank you.

 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);
    }
DNA
  • 42,007
  • 12
  • 107
  • 146
user2735714
  • 131
  • 7
  • 1
    This is more of a stylistic choice, but the code would be easier to read if you used a simple while loop (where the loop BEGINS with "while") instead of a do-while loop. – Sildoreth Feb 20 '15 at 19:12
  • Do you always get the EOF error? Or just sometimes? – Sildoreth Feb 20 '15 at 19:17
  • What is your "input"? Can you wrap it in a Scanner and do readLine(). It will pretty much block until it receives a message. So you don't have to poll and waste CPU. – lupus137 Feb 20 '15 at 19:20
  • Well, i get the EOF exception always if the message is not equal to "you have successfully logged in". And I don't know if i can replace it with scanner. I am using this function in the client of my application that is responding to a server. Actually this is another question that i have when should I choose ObjectInput/Output streams instead of Scanner and Formatter – user2735714 Feb 20 '15 at 19:49

2 Answers2

0

In your code sample, it looks like you have everything you should need. Just un-comment the line where you're setting eofReached.

Sildoreth
  • 1,883
  • 1
  • 25
  • 38
0

Well I found my mistake. The problem was that there was no such corresponding loop in the server to answer all of the requests. that's why I was getting the exception.

user2735714
  • 131
  • 7