Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class GetNeighbors
- {
- public static void main(String args[])
- {
- Scanner kb = new Scanner(System.in);
- System.out.println("Enter how many rows will be in the matrix");
- int row=kb.nextInt();
- System.out.println("Enter how many columns will be in the matrix");
- int col=kb.nextInt();
- int[][] mat=new int[row][col];
- initList(mat,row,col);
- while(assign(mat,row,col) >=0)
- {
- assign(mat,row,col);
- }
- }
- public static void initList(int[][] mat,int row,int col)
- {
- for(int r=0; r<row; r++)
- {
- System.out.println("");
- for(int c=0; c<col; c++)
- {
- mat[r][c]=(int)(Math.random()*1000+1);
- System.out.printf("%5s",mat[r][c]);
- }
- }
- }
- public static int assign(int[][] matrix,int row,int col)
- {
- int r = 0;
- int c = 0;
- Scanner keyboard=new Scanner(System.in);
- System.out.println("\nEnter the row number for an element");
- r=keyboard.nextInt();
- if(r == -1)
- {
- return -1;
- }
- System.out.println("Enter the column number for an element");
- c=keyboard.nextInt();
- if(r>=row || c >= col)
- {
- System.out.println("House does not exist");
- return 0;
- }
- System.out.println("Requested neighbors for element at row "+r+", col "+c+" "+"("+matrix[r][c]+")");
- if(r-1<row&&r-1>0)
- {
- System.out.println("North "+matrix[r-1][c]);
- }
- else
- {
- System.out.println("North -1");
- }
- if(r+1<row&&r+1>0)
- {
- System.out.println("South "+matrix[r+1][c]);
- }
- else
- {
- System.out.println("South -1");
- }
- if(c-1<col&&c-1>0)
- {
- System.out.println("West "+matrix[r][c-1]);
- }
- else
- {
- System.out.println("West -1");
- }
- if(c+1<col&&c+1>0)
- {
- System.out.println("East "+matrix[r][c+1]);
- }
- else
- {
- System.out.println("East -1");
- }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement