我正在尝试打印出一个2D数组,并确定起始元素的元素North,South,East和West。我已经用随机整数填充了数组,但如果方向超出界限而不是让整个程序崩溃,那么需要帮助打印“-1”用于该方向
import java.util.Scanner;
public class GetNeighbors
{
public static void printRow(int[]row)
{
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[]args)
{
Scanner kb=new Scanner(System.in);
System.out.println("Please enter a number of rows");
int r=kb.nextInt();
System.out.println("Please enter a number of columns");
int c=kb.nextInt();
int[][]spot=new int[r][c];
arrayWork(spot);
directionWork(spot);
}
public static void arrayWork(int[][]spot)
{
for(int i=0;i<spot.length;i++)
{
for(int j=0;j<spot[i].length;j++)
{
spot[i][j]=(int)(Math.random()*1001);
}
}
for(int[]row:spot)
{
printRow(row);
}
}
public static void directionWork(int[][]spot)
{
Scanner kb=new Scanner(System.in);
System.out.println("Please choose a row for an element");
int row=kb.nextInt();
System.out.println("Please choose a column for an element");
int col=kb.nextInt();
System.out.println("Requested neighbors for element at row "+row+", col "+col+" "+"("+spot[row][col]+")");
System.out.print("North: "+spot[row-1][col]);
System.out.print(" South: "+spot[row+1][col]);
System.out.print(" East: "+spot[row][col+1]);
System.out.print(" West: "+spot[row][col-1]);
}
}
答案 0 :(得分:0)
为避免重复一系列条件,您可以创建一个方法来检查行和列在检索值时是否在边界内:
public static int getElement(int[][] spot, int row, int col) {
if (row < spot.length && spot.length > 0 && row >= 0 && col < spot[row].length && spot[row].length > 0 && col >= 0) {
return spot[row][col];
} else {
return -1;
}
}
然后更改您的打印语句来调用它:
System.out.println("Requested neighbors for element at row "+row+", col "+col+" "+"("+getElement(spot, row, col)+")");
System.out.print("North: "+ getElement(spot, row - 1, col));
System.out.print(" South: " + getElement(spot, row + 1, col));
System.out.print(" East: " + getElement(spot, row, col + 1));
System.out.print(" West: "+ getElement(spot, row, col - 1));