我在尝试找出如何为字符编码传感器程序时遇到问题,主要是因为有一个名为“ loc”的变量。该API很有帮助,但是由于变量以Location.java及其方法为中心,该方法基本上具有代表(row,col)的变量,因此我在如何分别表示行/列方面遇到了麻烦。自从我过去做过MineSweeper程序以来,我从理论上就知道如何在2D数组中进行邻居测试,但是我不允许在这里更改任何变量。以下是问题这一部分的提示,位置的代码以及提示之一的方法名称。如果不做这部分,则不允许编写其余问题的代码。任何帮助将不胜感激。谢谢!
“写一个采用2D字符数组,指定行和列索引的位置以及一个字符的传感器方法, 如果在给定(row,col)坐标的四个邻居中的任何一个中找到该字符,则返回一个布尔值。 考虑6x5数组:
r\c# 0 | 1 | 2 | 3 | 4 |
===#===|===|===|===|===|
0 # | | | | |
1 # | | | | |
2 # | i | b | j | |
3 # | a | x | c | |
4 # | l | d | k | |
5 # | | | | |
例如,给定row = 3,Column = 2(用'x'标记)的Location(3,2),字符a,b,c和d被视为在坐标(3,1)处的邻居, (2,3),(3,3)和(4,2)。 字符i,j,k,l不被视为对角线上的邻居。
因此,鉴于上述矩阵和loc =(3,2),对“ sensor(matrix,loc,'a')”的调用将返回true, 而“ sensor(matrix,loc,'j')”将返回“ false”。 那是'a'是'x'的邻居,但是对角线上的'j'不被认为是该模型的邻居。”
public static boolean sensor(char[][] world, Location loc, char test)
Location.java:
/**
* @class This class holds the cell indices (row, column) for a 2D array
*/
import java.util.Random;
public class Location {
/** row of the array */
public int row;
/** column of the array */
public int col;
/** Private instance of random number generator */
private static Random rand = new Random();
/** Construct location at (0, 0) */
public Location() {
row = 0;
col = 0;
}
/**
* Copy constructor
*
* @param loc
* location to copy
*/
public Location(Location loc) {
row = loc.row;
col = loc.col;
}
/**
* Construct location at given coordinates
*
* @param i
* i^th row
* @param j
* j^th column
*/
public Location(int i, int j) {
row = i;
col = j;
}
/**
* Construct location at random point within max width (w) and height (h)
*
* @param height
* = height (number of rows)
* @param width
* = width (number of columns)
* @param random
* boolean flag to generated a random number otherwise (0,0)
*/
public Location(int height, int width, boolean random) {
if (random) {
row = rand.nextInt(height);
col = rand.nextInt(width);
}
}
/**
* formatted string that shows the row and column data
*
* @return formatted String
*/
@Override
public String toString() {
return String.format("(% 2d, % 2d)", row, col);
}
/**
* Compare two locations
*
* @param loc
* @return true if row and col values are equal, false otherwise
*/
@Override
public boolean equals(Object loc) {
if (loc == null) {
return false;
}
if (loc.getClass() != getClass()) {
return false;
}
Location loc2 = (Location) loc;
return (loc2.row == row) && (loc2.col == col);
}
/**
* Clones existing location and creates a new instance
*
* @return reference to the new instance
*/
@Override
public Location clone() {
return new Location(row, col);
}
}