2013-01-21 50 views
1

我有一個簡單的問題,我正在製作一個在線遊戲(在我移動到GUI之前讓基礎知識掌握)並且我有一些命令,例如,如果用戶在控制檯輸入'q',程序將終止(將相當),但如果錯誤發生在代碼的其他地方(即不能找到服務器),我關閉所有連接/嘗試的連接。我也想關閉掃描儀對象,但掃描儀對象保持在「.next()」方法中。我試着調用「.close()」和「.reset()」等,但沒有任何東西會使掃描器對象停止。如何停止掃描儀對象,以便完全關閉程序?在執行.next()方法時關閉掃描儀對象? java

-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()」。如何在不輸入任何內容的情況下關閉它?

+0

這裏沒有足夠的信息來回答。這些流是什麼?同儕代碼是什麼樣的?而你要找的詞是「退出」,而不是「相當」。 – EJP

回答

0

您不關閉掃描儀對象,因爲它不在try-block中。

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

應包括

scanCommands.close(); 

如果拋出一個異常,包括你的問題。

0

作爲一種快速解決方法,您可以在每次調用下一個方法之前嘗試檢查hasNext。