2015-09-11 104 views
0

嗨,我很新的編程,今天實際上是我的第三天到Java世界。每當我用掃描器寫一個java程序時,我都會發出警告「掃描儀永遠不會關閉」。請指出我做錯了什麼。掃描儀沒有關閉錯誤

public class App { 

    public static void main(String[] args) { 
     Scanner scanner = new Scanner(System.in); 
     System.out.println("what is your lucky number?"); 
     int my = scanner.nextInt(); 

     switch(my) { 
     case 7 : 
      System.out.println("your choice is correct"); 
      break; 
     case 10 : 
      System.out.println("your choice is correct"); 
      break; 
     default : 
      System.out.println("bad choice"); 
     } 
    } 
} 
+0

請問* *編譯器發出的警告,或者你在運行時得到它? –

回答

0

只需在代碼末尾添加scanner.close()即可。

+0

感謝它的完美工作 –

3

有一個警告,因爲您的工具(編譯器或IDE?)是足夠聰明地看到,有是實現Closeable,你的情況Scanner一個對象,你沒有調用的方法close()。實施Closeable的類會這樣做,因爲通常close()可釋放重要的系統資源,否則這些系統資源將被泄漏。例如,使用後需要關閉套接字或文件句柄。沒有關閉任何需要implemresources被關閉的模式:

Scanner scanner = null; 
try { 
    scanner = new Scanner(System.in); 
    // use the scanner 
} finally { 
    if (scanner != null) { 
     scanner.close(); 
    } 
} 

finally塊是保證執行,即使在try塊拋出的異常的任何一個Java版本。這確保您不會泄漏資源。

在Java 7+

try (Scanner scanner = new Scanner(System.in)) { 
    // use the scanner 
} 
+2

嘗試與資源是在Java 7中引入的,而不是8。 – Pshemo

+1

雖然它是相對常見的,但「java <8」方法的特定變體總是令我感到厭煩。由於'new'操作符不會產生'null',所以最好在try塊之前立即對對象進行實例化,然後不用擔心在關聯的'finally'塊中進行'null'測試。 –

+0

@JohnBollinger如果你的意圖不是添加一個catch塊,我會同意。如果構造函數拋出一個你想要捕捉的異常,使用我提供的模式通常很方便。 – Samuel