如何使用 java.awt 中的 Point 类查找二维数组的点



我在Map类中有一个二维字符数组

public class Map {
private char[][] map;
}

大小为 5 行和列(在构造函数中定义(。我在同一个类中也有一个方法

public Point findStart(){
Point location=new Point();
for ( int i=0; i<map.length; i++){
if(map[i][i]=='s')
System.out.println( "The starting position is in " + location.x + location.y );
}
return location;
}

它遍历数组以查找"s"字符。一旦它找到了字符,我希望利用java.awtPoint类来找到字符's'所在的位置。我怎样才能得到打印出来的要点?

正如 MaxG 所指出的,我的代码缺少一个 for 循环。新方法是

public Point findStart(){
Point location=new Point();
for ( int i=0; i<map.length; i++ ){
for( int j=0; j<map[i].length; j++ )
if(map[i][j]=='s')               
location.getLocation();
}
System.out.println(location.x+","+location.y);
return location;
}

不过,我仍然得到 0,0 作为坐标。

更新:我认为克里斯托弗·张伯伦提出了一个有效的观点。在项目中,我正在读取.txt文件并将每个字符放入数组中。

//loads maps according to an integer parameter, which depends on what map the player is in (Map1, Map2, Map3, etc.)
public void loadMap(int MapNum){
//attemps to load .txt file
try{
String s="Map"+MapNum+".txt";
File file=new File(s);
Scanner sc=new Scanner(file);       
while(sc.hasNextLine())
{          
for( int i=0; i<5; i++){
char currentCharacter=sc.next().charAt(0);
map[i][i]=currentCharacter;                           
}  
}      
}
catch(IOException exception){
System.out.println(exception);
}
}

此方法存在于同一类中。在阅读每个字符时,我可能会在某个地方搞砸,但我不知道在哪里?

你在寻找这样的东西吗?

public Point findStart() {
Point location = new Point();
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == 's') {
location.setLocation(i, j);
break;
}
}
}
System.out.println(location.x + "," + location.y);
return location;
}

最新更新