2013-07-06 52 views
0

我看了一下,我似乎無法找到答案。我創建了一個程序,輸入與棋盤相對應的數字,並一直給出答案,直至打印錯誤報告的最大數量。我無法解決關閉掃描儀的問題。我很新的Java和需要一些幫助,我的代碼:我無法關閉掃描儀

while (true) { 

//learned the import scanner from Greg and managed to get it working with my code :) 
System.out.println("Please select chess square from 1 - 25"); 
Scanner scan = new Scanner(System.in); 
final int SIZE = 5; 
//the plus one makes it start in the correct point 
int SQUARENUM = scan.nextInt()+1; 

int grains = 1; 
int j = 1; 
int tGrains = 0; 


if (SQUARENUM > 26){ 
    System.out.println("****************---------------****************"); 
    System.out.println("** ERROR Only 25 squares to choose from ERROR **"); 
    System.out.println("****************---------------****************"); 

    continue;} 

//still trying to get it to close without the error. 
//if(scan!=null) 
//scan.close(); 


System.out.println("The amount of squares on the 5 by 5 board is: " + (SIZE*SIZE)); 
System.out.println("Looking at Square:"+(SQUARENUM - 1)); 

while(j < SQUARENUM){   
    System.out.println("Grains of wheat on square:" + j + " is:" + grains); 
    grains *= 2; 
    tGrains = tGrains + grains; 
    j++;   
} 
System.out.println(" *** Total Grains of Wheat = " + (tGrains/ 2) + " ***"); 
} 

回答

0

要關閉Scanner通話close您使用完之後。

一般來說,您應該在try-catch-finally塊中訪問您的掃描器,並關閉finally塊中的掃描器,以確保它始終關閉。

的教程,請參閱here使用Scanner

您可能還需要在Java 7中

+0

使用try-catch來關閉掃描儀是正確的,但這不是他的問題的根源,因爲您可以在不使用try塊的情況下使用close()。 –

+0

謝謝,這很有幫助。我已經得到它的工作:) –

1

檢查出try with resource功能循環的第一次迭代將被罰款,你將能夠做到

scan.close(); 

問題是當循環進入第二次迭代時。你叫

scan.nextInt(); 

後您關閉掃描儀。關閉後您不能再次使用掃描儀。 所以你應該將scan.close()移到循環之外。