【问题标题】:How to find numbers that are North South East and West of a number in a 2D array如何在二维数组中查找数字的南北东和西的数字
【发布时间】:2016-01-26 02:10:54
【问题描述】:

到目前为止,我的程序可以找到指定位置的南北东和西的数字,但是如果我在程序中输入没有 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);
}

【问题讨论】:

  • 错误是什么,是什么输入导致了这个错误?
  • array[0][0] 以北是什么地方?
  • 这应该是java 吗?没有语言标签。
  • 是的,它是 java,数组也填充了随机数和用户输入的行大小和列大小

标签: arrays loops for-loop 2d


【解决方案1】:

您很可能会遇到越界异常。当您检查北时,您需要检查rw-1&gt;=0,因为您不能在数组中引用负索引。同样在 west 方法中,您需要检查 cl-1&gt;=0。在 south 和 east 方法上,您需要检查是否超出了数组的长度。在南方你需要检查你的rw+1&lt;= array.length,在东方你需要检查cl+1&lt;= 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");
  }

}

【讨论】:

  • 它没有工作,因为它仍然给我同样的错误
  • (越界) public static void fetchN(int[][]array , int rw, int cl) { int north=0; for(int r = 0; r =0){北=数组[rw-1][cl]; System.out.print("北::"+北); } else { System.out.print("没有北坐标"); } } } }
  • nvm比你好很多
猜你喜欢
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 2012-01-21
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
相关资源
最近更新 更多