2016-02-29 56 views
-2

我得到了輸入文件名的命令行參數,並且我已經使用Scanner Connection inorder從該文本文件讀取輸入,並且在執行操作後,我關閉了掃描器連接。 NZEC(運行時錯誤)。掃描器中的連接未關閉

在我的機器,我用更少的投入工作,所以錯誤重現因此未但是在在線編程競賽網站上的錯誤是發生

索爾:如果我使用一個try-catch,問題就解決了。

但請建議我這樣做的原因錯誤

Whats_next() 
{ 
    Scanner s=new Scanner(System.in); 
    while(s.hasNextLine()) 
    { 
    int x=s.nextInt(); 
    int y=s.nextInt(); 
    int z=s.nextInt(); 
    if(x!=0 || y!=0 || z!=0) 
    { 
     if((y-x)==(z-y)) 
      { 
       System.out.print("AP"); 
       System.out.println("\t"+(z+(y-x))); 
      } 
     else if((y/x)==(z/y)) 
      { 
       System.out.print("GP"); 
       System.out.println("\t"+z*(y/x)); 
      } 
    } 
    } 
    s.close(); 
} 


    public static void main(String[] args) 
    { 
    try 
    { 
     if(args.length==1) 
      System.setIn(new FileInputStream(args[0])); 
    } 
    catch(Exception e) 
    { 

    } 
     Whats_next w=new Whats_next(); 
    } 
+2

當你關閉你的'Scanner'時,它也關閉'System.in'(你不能在此之後重新打開'System.in')。 –

+0

請勿在比賽網站上設置System.in,並且不要關閉掃描儀。 – Bob

回答

0

你應該關閉在finally塊的連接。

try { 
    Scanner scanner = new Scanner(System.in); 
    // your logic 
} 
finally { 
    if(scanner!=null) 
     scanner.close(); 
} 
+0

是否有必要使用try-catch-finally塊,如果我們正常關閉爲什麼它不接受。請給我回答 – Rakesh

+0

建議關閉finally塊中的連接,因爲如果你有多個catch塊,你將有重寫conn.close() 無論發生什麼事情,fin​​ally塊總會在嘗試後執行。所以如果你得到一個你沒有處理的異常,那麼在finally塊中,你將確保你的資源被正確關閉。 – FallAndLearn