Write a program ShiftNumbers.java that takes integer M as the number of both rows and columns for your 2D array. Create the same exact following 2D array. Note: The borders are produced at the time of printing. You also need to shift the numbers for each row of the 2D array as displayed below:+-+-+-+-+-+|1|2|3|4|5|+-+-+-+-+-+|2|3|4|5|1|+-+-+-+-+-+|3|4|5|1|2|+-+-+-+-+-+|4|5|1|2|3|+-+-+-+-+-+|5|1|2|3|4|+-+-+-+-+-+. kinda, dont worry about the added spaces inbetween.

Answer :

ammary456

Answer:

import java.util.Scanner;

public class ShiftNumbers {

public static void movearr(int[][] arr, int move) {

for (int row = 0; row < arr.length; row++) {

int lengthOfRow = arr[row].length;

move = move % lengthOfRow;

int[] tmp = new int[move];

for (int i = 0; i < move; i++) {

tmp[i] = arr[row][i];

}

for (int col = 0; col < lengthOfRow - move; col++) {

arr[row][col] = arr[row][col + move];

}

for (int i = 0; i < move; i++) {

arr[row][i + (lengthOfRow - move)] = tmp[i];

}

}

}

public static void main(String []args){

System.out.println("Hello World");

int M=5;

int[][] arr1 = new int[M][M];

Scanner in=new Scanner(System.in);

System.out.println("Enter the 2 D arr elements");

for(int i=0;i<M;i++){

for(int j=0;j<M;j++){

arr1[i][j]=in.nextInt();

}

}

movearr(arr1, 1);

for (int[] row : arr1) {

for (int col : row) {

System.out.print(col);

}

System.out.println();

}

}

}

Explanation:

  • Inside the ShiftNumbers class, use a for loop which runs within bounds of the arr ay.
  • Inside the main method, run a nested for loop to take 2D array as an input from user.
  • Clone the elements that will fall off , move as usual and then clone the fall off elements  again.
  • Call the movearr method and then display the results.

Other Questions