2013-07-06 51 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()移到循环之外。