在方法public boolean onMap(Coord c)
中,如何确定给定的Coord
c是否在此Map
上(Map
也是一个类)?这两个类都在下面。
import java.io.*;
import java.util.Scanner;
public class Map {
Spot[][] floorPlan;
Thing[] things;
java.io.PrintStream log;
Map(String fileName, PrintStream log) throws IOException
{
String line = "";
int cols = 0;
int rows = 0;
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
line = data.nextLine();
cols = line.length();
rows++;
}
floorPlan = new Spot[rows][cols];
}
public boolean onMap(Coord c)
{
return true;
}
}
public class Coord {
public final int r;
public final int c;
public Coord(int r, int c)
{
this.r = r;
this.c = c;
}
public Coord step(Direction d)
{
if(d == Direction.N)
{
Coord newValue = new Coord(r + 1, c);
return newValue;
}
else if(d == Direction.S)
{
Coord newValue = new Coord(r - 1, c);
return newValue;
}
else if(d == Direction.E)
{
Coord newValue = new Coord(r, c + 1);
return newValue;
}
else if(d == Direction.W)
{
Coord newValue = new Coord(r, c - 1);
return newValue;
}
else
return this;
}
public Coord copy()
{
Coord clone = new Coord(r, c);
return clone;
}
public boolean equals(Object o)
{
if(o instanceof Coord)
{
Coord newValue = (Coord)o;
return this.r == newValue.r && this.c == newValue.c;
}
else
return false;
}
public boolean adjacent(Coord other)
{
Coord temp1 = new Coord(r + 1, c);
Coord temp2 = new Coord(r - 1, c);
Coord temp3 = new Coord(r, c + 1);
Coord temp4 = new Coord(r, c - 1);
if(temp1.r == other.r && temp1.c == other.c)
return true;
else if(temp2.r == other.r && temp2.c == other.c)
return true;
else if(temp3.r == other.r && temp3.c == other.c)
return true;
else if(temp4.r == other.r && temp4.c == other.c)
return true;
else
return false;
}
public String toString()
{
return String.format("\"@(%d,%d)\"", r,c);
}
}
答案 0 :(得分:0)
蓝色的猜测是你想要做一些叫做边界检查的事情。 (如果不是这样,请告诉我)
由于Spot[][]
是一个数组数组,floorPlan[i]
实际上是另一个数组(具有独立边界)。因此,检查是否
floorPlan[r][c]
不会抛出ArrayIndexOutOfBoundsException
,您需要首先检查r
上的floorPlan
,然后c
上的floorPlan[r]
:
if (r < 0 || r >= floorPlan.length) return false;
if (c < 0 || c >= floorPlan[r].length) return false;
return true;
然而,实际提供Map
属性width
和height
并始终强制执行floorPlan[r].length = width
和floorPlan.length = height
可能更为自然。为了获得更好的代码,你不应该从类外部提供私有变量,而是提供合理的getter和setter(甚至可以调整Map
的大小而不丢失其内容的功能?)