基本上每个房间的大小都是10乘10,"W"代表墙,空格-"代表楼层,数字是门。我认为创建房间的最佳方法是创建一个方法,接收文件并读取它,并将其"信息"放入String[10][10]中,然后创建另一个方法(或者只在我的Main中执行),该方法接收创建的String[10][10]并创建房间(将图像添加到房间中),但我在阅读文件时遇到了一些困难,所以如果你们能帮助我完成这一部分,我将不胜感激。这是我想创建房间的文本文件类型:
WWWW0WWWWW
W W
W W
W W
W W
W WW
W WW
W WW
W W1
WWWWWWWWWW
以下是门、墙和地板类:
public class Door implements ImageTile {
private Position position;
public Door(Position position) {
this.position = position;
}
@Override
public String getName() {
return "Door";
}
@Override
public Position getPosition() {
return position;
}
}
public class Floor implements ImageTile {
private Position position;
public Floor(Position position) {
this.position = position;
}
@Override
public String getName() {
return "Floor";
}
@Override
public Position getPosition() {
return position;
}
}
public class Wall implements ImageTile {
private Position position;
public Wall(Position position) {
this.position = position;
}
@Override
public String getName() {
return "Wall";
}
@Override
public Position getPosition() {
return position;
}
}
这是我在相框中添加图像的方法:
public void newImages(final List<ImageTile> newImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
frame.repaint();
}
如果你们能帮我,我会非常感激,谢谢你们。她就是我现在拥有的:
public class Room {
private String[][]room;
public Room(){
room = new String[10][10]; }
public static Room fromFile(File file){
if(file.exists()){
Scanner sc = null;
Room room = new Room();
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if(sc.nextLine().startsWith("#"))
sc.nextLine();
else{
String[] s0 = sc.nextLine().split("");
//Here is where my trouble is, i dont know how to add the content of this String s0 to the String s
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. "); }
finally{
if(sc!=null)sc.close();
}
}
else
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. ");
return null;
}
每次对sc.nextLine()
的调用都会从文件中读取另一行。您需要将该行保存到一个临时变量中,然后引用该临时变量。
维护一个已处理行的计数器,以便您可以在s[][]
矩阵中填写相应的行。
您只需要为这10行分配存储,因为拆分读取的行将导致为您分配一个字符串数组(一行中的列)。
int row = 0;
String[][] s = new String[10][];
while(sc.hasNextLine() && i < 10) {
String line = sc.nextLine();
if( !line.startsWith("#")) {
String[] s0 = sc.line.split("");
s[row] = s0;
row++;
}
}
BTW,使用String[][]
是过度杀伤;因为每个字符串将只包含一个字符。也许您可以考虑使用char[][]
。line.toCharArray()
会为您将line
拆分为char[]
。
编辑:(由于编辑了您的问题代码)
代替:
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
}
你想要:
if(s0.length==10){
for(int y = 0; y < 10; y++){
s[row][y] = s0[y];
}
row++;
}
row
是我上面代码中的行计数器。