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) + " ***");
}
4

2 回答 2

1

循环的第一次迭代会很好,你将能够做到

scan.close();

问题是当循环进入第二次迭代时。你打电话给

scan.nextInt();

关闭扫描仪后。关闭扫描仪后,您将无法再次使用扫描仪。所以你应该移到scan.close()循环之外。

于 2013-07-06T13:17:19.123 回答
0

使用完毕后关闭Scanner通话。close

一般来说,您应该在 try-catch-finally 块中访问您的扫描器,并在 finally 块中关闭扫描器以确保它始终关闭。

有关使用的教程,请参见此处Scanner

您可能还想查看 Java 7 中的try with resource功能。

于 2013-07-06T13:08:43.840 回答