94.6k views
22 votes
You are asked to write a program that prompts the user for the size of two integer arrays, user input for the size must not exceed 50, you must validate this. We will use these arrays to represent our sets. These arrays will be randomly populated in the range that is 1 through double the size of the array. So if the array is of size 20, you will randomly populate it with values in the range 1-40 inclusive.

User HOCA
by
3.8k points

1 Answer

4 votes

Answer:

In Java:

import java.util.*;

public class MyClass{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Length of array 1: ");

int lent1 = input.nextInt();

while(lent1 <= 0 || lent1 > 50){

System.out.print("Length of array 1: ");

lent1 = input.nextInt();

}

int[] array1 = new int[lent1];

System.out.print("Length of array 2: ");

int lent2 = input.nextInt();

while(lent2 <= 0 || lent2 > 50){

System.out.print("Length of array 2: ");

lent2 = input.nextInt();

}

int[] array2 = new int[lent2];

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

array1[i] = (int)(Math.random() * (lent1*2) + 1);

}

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

array2[i] = (int)(Math.random() * (lent2*2) + 1);

}

System.out.print("Array 1: ");

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

System.out.print(array1[i]+" ");

}

System.out.println("Array 2: ");

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

System.out.print(array2[i]+" ");

}

}

}

Step-by-step explanation:

This prompts the user for length of the first array

System.out.print("Length of array 1: ");

This declares and gets input for the length of the first array

int lent1 = input.nextInt();

This validates the length of first array

while(lent1 <= 0 || lent1 > 50){

System.out.print("Length of array 1: ");

lent1 = input.nextInt(); }

This declares the first array

int[] array1 = new int[lent1];

This prompts the user for length of the second array

System.out.print("Length of array 2: ");

This declares and gets input for the length of the second array

int lent2 = input.nextInt();

This validates the length of the second array

while(lent2 <= 0 || lent2 > 50){

System.out.print("Length of array 2: ");

lent2 = input.nextInt(); }

This declares the second array

int[] array2 = new int[lent2];

The following generates random integers between 1 and lent1*2 to array 1

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

array1[i] = (int)(Math.random() * (lent1*2) + 1); }

The following generates random integers between 1 and lent2*2 to array 2

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

array2[i] = (int)(Math.random() * (lent2*2) + 1); }

This prints the header Array 1

System.out.print("Array 1: ");

The following iteration prints the content of the first array

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

System.out.print(array1[i]+" ");

}

This prints the header Array 2

System.out.println("Array 2: ");

The following iteration prints the content of the second array

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

System.out.print(array2[i]+" ");

}

User Inglis Baderson
by
3.7k points