該程序的要點是讀取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