我真的需要你的帮助。我想将 TXT 文件的字符放入多维数组,但我的 Java 代码并不能真正工作。我必须使用 Scanner.util 读取文件。这是我的代码
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
try {
FileInputStream file = new FileInputStream("a.txt");
Scanner s = new Scanner(file);
char arr[][];
while (s.hasNextLine()) {
String line = s.nextLine();
for (int i=1 ;i<=line.length(); i++){
for (int k=1 ;k<=line.length(); k++){
arr[k][i] = line.charAt(i); //the local variable arr may not have been initialized
}
}
for (int i=0 ;i<=line.length(); i++){
int k=0;
System.out.println (arr[i][k]); //the local variable arr may not have been initialized
k ++;
}
}
file.close();
} catch (IOException e) {
System.out.println("Fehler");
}
}
}
你能帮我更正我的代码吗?这将是非常好的:)
编辑:
好的。这就是它现在的样子:
public class Test {
public static void main(String args[]) {
try {
FileInputStream file = new FileInputStream("a.txt");
Scanner s = new Scanner(file);
char arr[][] = new char[15][9]; //changed
while (s.hasNextLine()) {
String line = s.nextLine();
for (int i=0 ;i<=line.length(); i++){ //changed
for (int k=0 ;k<=line.length(); k++){ //changed
arr[k][i] = line.charAt(i);
}
}
for (int i=0 ;i<=line.length(); i++){
int k=0;
System.out.println (arr[i][k]);
k ++;
}
}
file.close();
} catch (IOException e) {
System.out.println("Fehler");
}
}
}
这是我想读入的 TXT 文件:
---------------
|S | | |
| --- | ---- |
| | | | |
| | |---- |Z|
| | | | |
| | | | | |
| | | | |
---------------
但是如果我启动程序,我会得到这个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at maze.Test.main(Test.java:21)
你有什么想法,我做错了什么?-.-
好的。这就是它现在的样子:
public class Test {
public static void main(String args[]) {
try {
FileInputStream file = new FileInputStream("a.txt");
Scanner s = new Scanner(file);
char arr[][] = new char[15][9]; //changed
while (s.hasNextLine()) {
String line = s.nextLine();
for (int i=0 ;i<=line.length(); i++){ //changed
for (int k=0 ;k<=line.length(); k++){ //changed
arr[k][i] = line.charAt(i);
}
}
for (int i=0 ;i<=line.length(); i++){
int k=0;
System.out.println (arr[i][k]);
k ++;
}
}
file.close();
} catch (IOException e) {
System.out.println("Fehler");
}
}
}
这是我想读入的 TXT 文件:
---------------
|S | | |
| --- | ---- |
| | | | |
| | |---- |Z|
| | | | |
| | | | | |
| | | | |
---------------
但是如果我启动程序,我会得到这个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at maze.Test.main(Test.java:21)
你有什么想法,我做错了什么?-.-