Java 无接触异常二维阵列
我一直没有得到任何例外,但我不知道为什么。我知道错误是针对扫描仪的,但不知道发生此错误的原因。我包括了输入文件Java 无接触异常二维阵列,java,multidimensional-array,Java,Multidimensional Array,我一直没有得到任何例外,但我不知道为什么。我知道错误是针对扫描仪的,但不知道发生此错误的原因。我包括了输入文件 import java.util.*; import java.io.*; public class Numbrosia { static int [][] board = new int [5][5]; public static void main(String[]args){ Scanner scan = null; try{
import java.util.*;
import java.io.*;
public class Numbrosia {
static int [][] board = new int [5][5];
public static void main(String[]args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
return;
}
for(int row = 0; row<board.length; row++){
for(int col= 0; col<board.length;col++){
board[row][col] = scan.nextInt();
}
}
while(true){
showBoard();
System.out.println("");
System.out.println("Input number from 1 to 5: ");
int i = scan.nextInt();
System.out.println("Input move command: ");
String moveName = scan.next();
//If/ else statements to dictate which method to call
输入文件:
1 -2 1 0 0
-1 0 4 2 0
0 -4 1 -1 0
0 1 -1 -1 -2
0 -3 1 -1 0
因为扫描器在完成文件读取后没有被告知读取用户输入,所以它在向用户请求数字后仍在尝试读取文件。您需要创建一个新的扫描仪以从键盘读取数据。
对while循环使用以下代码:
scan.close();
Scanner kbScan = new Scanner(System.in);
while(true){
showBoard();
System.out.println("");
System.out.println("Input number from 1 to 5: ");
//This will read from the keyboard
int i = kbScan.nextInt();
System.out.println("Input move command: ");
String moveName = scan.next();
在需要从键盘读取的方法中的任何其他地方,使用
kbScan
而不是scan
可以发布更多的代码吗?在循环的第一次迭代中是否引发异常?我刚刚发布了更多的代码,它在哪一行给出了此异常
scan.close();
Scanner kbScan = new Scanner(System.in);
while(true){
showBoard();
System.out.println("");
System.out.println("Input number from 1 to 5: ");
//This will read from the keyboard
int i = kbScan.nextInt();
System.out.println("Input move command: ");
String moveName = scan.next();