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 100. The program must prompt the user to enter a search key between 1 and 100. Then, the program must check whether the search key is available in the array and print its location.

Respuesta :

Answer:

The program in Java is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 int x, y;

 System.out.print("x and y: ");

 x = input.nextInt(); y = input.nextInt();

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

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

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

         twoD_arr[i][j] = (int)(Math.random() * 100);      }  }

 System.out.print("Search: ");

 int numSearch = input.nextInt();

 int count = 0;

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

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

         if(twoD_arr[i][j] == numSearch){

             count++;

             System.out.println("Row "+(1+i)+" Column "+(j+1));          }          }    }

 if(count == 0){ System.out.print("Key does not exist");  }

}

}

Explanation:

Declare x and y

 int x, y;

Prompt user for x and y

 System.out.print("x and y: ");

Get input for x and y

 x = input.nextInt(); y = input.nextInt();

Declare the two dimensional array

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

Iterate through the rows

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

Iterate through the columns

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

Get input for each cell

         twoD_arr[i][j] = (int)(Math.random() * 100);      }  }

Prompt the user for search key

 System.out.print("Search: ");

Get input search key

 int numSearch = input.nextInt();

Initialize count to 0

 int count = 0;

Iterate through the rows

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

Iterate through the columns

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

Check if current element and the search key are the same.

         if(twoD_arr[i][j] == numSearch){

Increment count by 1, if they are the same

             count++;

Print the position

             System.out.println("Row "+(1+i)+" Column "+(j+1));          }          }    }

If count is 0, print key does not exist

 if(count == 0){ System.out.print("Key does not exist");  }