该程序的要点是读取txt文件中的字符并将它们存储到二维数组中。完成此操作后,将以与从txt文件中读取相同的方式打印信息。打印二维数组的内容
这里是我的代码至今:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("sampleMaze.txt");
Scanner s = new Scanner(file);
Maze maze = new Maze(s);
System.out.print(file);
}
}
import java.io.File;
import java.util.Scanner;
import java.util.Arrays;
public class Maze {
public int width;
public int height;
public Square [] [] sampleMaze;
Maze(Scanner file) {
this.width = Integer.parseInt(file.next());
this.height = Integer.parseInt(file.next());
this.sampleMaze = new Square [height] [width];
for (int i = 0 ; i < height ; i++) {
String s = file.next();
for (int j = 0 ; j < width ; j++) {
sampleMaze[height][width] = Square.fromChar(s.charAt(j));
}
}
System.out.print(sampleMaze[height][width]);
}
}
public enum Square {
WALLS("#"),
OPEN_SPACES("."),
START("o"),
FINISH("*");
String x;
Square(String x) {
this.x = x;
}
public String toString() {
return x;
}
public static Square fromChar(char x) {
if (x == '#')
return WALLS;
else if (x == '.')
return OPEN_SPACES;
else if (x == 'o')
return START;
else if (x == '*')
return FINISH;
else
throw new IllegalArgumentException();
}
}
这是努力实现项目的目标,当我收到错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "############"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Maze.<init>(Maze.java:15)
at Main.main(Main.java:20)
任何人都知道这是怎么回事在这里以及我如何纠正这个?
(这是在sampleMaze.txt文件),我需要为它做的是打印这样的:
当你分析你的宽度和高度则trowing NumberFormatException异常整型,这意味着不管它是从文件中读取心不是要分析 – JRowan 2014-10-10 23:01:59
更具体的int,它是字符串“############”,表明输入文件中缺少宽度和高度。 – 2014-10-10 23:02:59
所以我应该写这样的代码: this.width = Character.parseChar(file.next()); this.height = Character.parseChar(file.next()); – Wes 2014-10-10 23:04:06