Write a Java program that creates a two-dimensional array of type integer of size x by y (x and y must be entered by the user). The program must fill the array with random numbers from 1 to 9. Then, the program must print the original array and the elements that are in even columns of the array.

Respuesta :

Answer:

The java program is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 Random r = new Random();

 int x, y;

 x = input.nextInt();  

 y = input.nextInt();

 int[][] Array2D = new int[x][y];

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

     for(int j = 0; j < y; j++){          Array2D[i][j] = r.nextInt(9) + 1;      }

 }

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

     for(int j = 0; j < y; j++){          System.out.print(Array2D[i][j]+" ");      }

     System.out.println();

 }

 

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

     for(int j = 1; j < y; j+=2){          System.out.print(Array2D[i][j]+" ");      }

     System.out.println();

 }

}

}

Explanation:

This creates a random object

 Random r = new Random();

This declares x and y as integers

 int x, y;

This gets input for x

 x = input.nextInt();  

This gets input for y

 y = input.nextInt();

This declares the 2D array

 int[][] Array2D = new int[x][y];

The following iteration populates the array with integers 1 to 9

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

     for(int j = 0; j < y; j++){          Array2D[i][j] = r.nextInt(9) + 1;      }

 }

The following iteration prints all elements of the array

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

     for(int j = 0; j < y; j++){          System.out.print(Array2D[i][j]+" ");      }

     System.out.println();

 }

The following iteration prints all elements on the even column

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

     for(int j = 1; j < y; j+=2){          System.out.print(Array2D[i][j]+" ");      }

     System.out.println();

 }