I have a two dimensional character array in a Map
class
public class Map {
private char[][] map;
}
which is 5 rows and columns in size (defined in a constructor). I also have a method in the same class
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;
}
which iterates through the array to find the "s"
character. Once it locates the character, I wish to make use of java.awt
's Point
class to find the location of where the char 's' is located. How can I get the point to print out?
As MaxG has pointed out, my code is missing a for loop. The new method is
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;
}
I still get 0,0 as coordinates though.
UPDATE: I think Christopher Chamberlain brings up a valid point. In the project I am reading from a .txt file and placing each character into the array.
//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);
}
}
this method exists in the same class. I could be messing up somewhere while reading each character but I cannot figure out where?
Are you looking for somehting like this ?
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;
}
I don't have enough reputation to comment... sorry...
Jaydip's solution looks like the way to do it. The only reason it wouldn't work is if map[i][j] == 's'
never returns true
. Are you sure map
contains an 's'
? I think the problem has to do with how you fill map
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.