如何在二维数组中查找数字的东南北和西
How to find numbers that are North South East and West of a number in a 2D array
到目前为止,我的程序可以找到指定位置的北东南和西的数字,但是如果我在程序中输入没有 n、s、e、w 值的数字,它会给我一个错误。有人可以帮忙吗?
这是我的北方方法的一个例子
public static void fetchN(int[][]array , int rw, int cl)
{
int north = 0;
int east = 0;
int south = 0;
int west = 0;
for(int r = 0; r < array.length; r++)
{
for(int c = 0; c < array[r].length; c++)
{
north = array[rw-1][cl];
}
}
System.out.print("North :: "+north);
}
您很可能遇到越界异常。当你检查 north 时,你需要检查 rw-1>=0
因为你不能引用数组中的负索引。同样在 west 方法中,您需要检查 cl-1>=0
。在 south 和 east 方法中,您需要检查是否超出了数组的长度。在南面,您需要检查 rw+1<= array.length
,在东面,您需要检查 cl+1<= array[rw].length
.
您的方法似乎也有一些冗余代码。您的两个 for 循环都没有在这里完成任何事情,并且您正在初始化不必要的变量。这是您的 fetchN 方法的重写版本。
public static void fetchN(int[][]array , int rw, int cl)
{
if(rw-1>=0){
int north = array[rw-1][cl];
System.out.print("North :: "+north);
}
else{
System.out.print("There is no North coordinate");
}
}
到目前为止,我的程序可以找到指定位置的北东南和西的数字,但是如果我在程序中输入没有 n、s、e、w 值的数字,它会给我一个错误。有人可以帮忙吗?
这是我的北方方法的一个例子
public static void fetchN(int[][]array , int rw, int cl)
{
int north = 0;
int east = 0;
int south = 0;
int west = 0;
for(int r = 0; r < array.length; r++)
{
for(int c = 0; c < array[r].length; c++)
{
north = array[rw-1][cl];
}
}
System.out.print("North :: "+north);
}
您很可能遇到越界异常。当你检查 north 时,你需要检查 rw-1>=0
因为你不能引用数组中的负索引。同样在 west 方法中,您需要检查 cl-1>=0
。在 south 和 east 方法中,您需要检查是否超出了数组的长度。在南面,您需要检查 rw+1<= array.length
,在东面,您需要检查 cl+1<= array[rw].length
.
您的方法似乎也有一些冗余代码。您的两个 for 循环都没有在这里完成任何事情,并且您正在初始化不必要的变量。这是您的 fetchN 方法的重写版本。
public static void fetchN(int[][]array , int rw, int cl)
{
if(rw-1>=0){
int north = array[rw-1][cl];
System.out.print("North :: "+north);
}
else{
System.out.print("There is no North coordinate");
}
}