我有一个像这样的文本文件:
10, 11.
(0, 0).
(3, 10).
(0, 6), (0, 7), (0, 9),
(1, 1), (1, 2), (1, 4), (1, 7),
(2, 1), (2, 7), (2, 8), (2, 10),
(3, 1), (3, 2), (3, 3), (3, 4), (3, 7),
(4, 0), (4, 6), (4, 9), (4, 10),
(5, 2), (5, 3), (5, 4), (5, 5), (5, 7),
(6, 1), (6, 8), (6, 9),
(7, 1), (7, 2), (7, 3), (7, 6),
(8, 1), (8, 5), (8, 6), (8, 8), (8, 10),
(9, 3), (9, 7).
第一行给出2 d数组的尺寸,第二行应该等于“S”,第三行等于“F”,所有其他行等于应该为“X”的点,任何未列出的数据应该是“”
我仍然需要在代码中添加更多内容,因此任何未使用的变量都是为了这个,我只是想获得我必须首先运行的东西
到目前为止,我得到的错误是:
线程“main”中的异常java.util.InputMismatchException at java.util.Scanner.throwFor(未知来源)at java.util.Scanner.next(未知来源)at java.util.Scanner.nextInt(未知来源)at java.util.Scanner.nextInt(未知来源)at MazeOne.main(MazeOne.java:15)
当我尝试在不读取文本文件的情况下运行类似的代码并打印数组时,它也给了我这样奇怪的东西而不是数组:
[[Ljava.lang.String;@55f96302, [Ljava.lang.String;@3d4eac69, [Ljava.lang.String;@42a57993, [Ljava.lang.String;@75b84c92]
到目前为止我的代码看起来像:
非常感谢任何有关我出错的建议或帮助
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
import java.util.Scanner;
public class MazeOne {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
int HEIGHT, LENGTH;
//Get file name from keyboard
File importFileName = new File("MazeOne.txt");
Scanner inFile = new Scanner("MazeOne.txt");
int Height = inFile.nextInt();
int Length = inFile.nextInt();
HEIGHT = Height-1;
LENGTH = Length-1;
String [][] MazeArray = new String[HEIGHT][LENGTH];
String [][] Start = new String[][]{{".",".","."},{".","S","."},{".",".","."}};
String [][] Block = new String[][]{{"X","X","X"},{"X","X","X"},{"X","X","X"}};
String [][] Finish = new String[][]{{".",".","."},{".","F","."},{".",".","."}};
String [][] Normal = new String[][]{{".",".","."},{".",".","."},{".",".","."}};
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < LENGTH; j++)
{
MazeArray[i][j] = ".";
}
}
if(inFile.hasNextLine())
{
int X = inFile.nextInt();
int Y = inFile.nextInt();
MazeArray[Y][X] = "S";
}
if(inFile.hasNextLine())
{
int X = inFile.nextInt();
int Y = inFile.nextInt();
MazeArray[Y][X] = "F";
}
while(inFile.hasNextLine())
{
while(inFile.hasNextInt()){
int X = inFile.nextInt();
int Y = inFile.nextInt();
MazeArray[Y][X] = "X";
}
}
System.out.print(MazeArray);
}
}
答案 0 :(得分:1)
在打印阵列时使用此Arrays.toString(arrayName)
。
答案 1 :(得分:1)
<强>第一强>
扫描仪应采用文件:
Scanner inFile = new Scanner(new File("path\\MazeOne.txt"));
不像你那样String
:
Scanner inFile = new Scanner("MazeOne.txt");
您已经定义了文件,因此您可以使用:
Scanner inFile = new Scanner(importFileName);
第二
Scanner的默认分隔符是一个空格,因此当您尝试使用:
时int Height = inFile.nextInt();
int Length = inFile.nextInt();
这可能会出现问题,因为分隔符不正确我建议删除输入之间的逗号10 11
与其他输入(0, 0).
和...
我建议您输入没有任何特殊字符,而不是使用
10 11
0 0
3 10
0 6 0 7 0 9
1 1 1 2 1 4 1 7
2 1 2 7 2 8 2 10
3 1 3 2 3 3 3 4 3 7
4 0 4 6 4 9 4 10
5 2 5 3 5 4 5 5 5 7
6 1 6 8 6 9
7 1 7 2 7 3 7 6
8 1 8 5 8 6 8 8 8 10
9 3 9 7
<强>第三强>
您将获得java.lang.ArrayIndexOutOfBoundsException: 10
例外,因为您有12行,并且只使用10
初始化数组
<强>第四强>
要打印阵列,您需要使用循环,或者您可以使用:
Arrays.deepToString(MazeArray)
注意请勿在变量的第一个字符中使用大写字母。
解决此问题,您将解决问题