[英]How to find the point of a two dimensional array using the Point class in java.awt
我在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.awt
的Point
類找到char所在位置的位置。 我該如何打印出來?
正如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;
}
我沒有足夠的聲譽來發表評論...對不起...
Jaydip的解決方案看起來就像是這樣做的方法。 它不起作用的唯一原因是map[i][j] == 's'
從不返回true
。 您確定map
包含's'
嗎? 我認為問題與您如何填寫map
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.