In: Computer Science
Java Programming. I'm writing this in an IDE called Eclipse.
If you could also use comments to help me understand the code / your way of thinking, I'd highly appreciate your efforts.
This needs to use a for each loop, it will generates and return= an array of random 2-digit integers and it also needs to be printed out all on one line, separated by spaces.
Program71:
Write a program with a custom method that generates and returns an array of random 2-digit integers. The main method should prompt the user to specify the size of the array and call the custom method with this input as an argument. Use a foreach loop in main to display the integers all on one line separated by spaces.
Sample Output (user input in blue)
How many random 2-digit integers are desired?
12
Here are your integers:
43 76 22 38 64 30 87 14 55 63 35 42
I have written the program using JAVA PROGRAMMING LANGUAGE.
OUTPUT :
CODE :
// imported the required modules random and scanner
import java.util.Random;
import java.util.Scanner;
//Main class
class Main {
//method definition for generateRandom
static int[] generateRandom(int input)
{
int[] output = new int[input]; //return variable
int rand_int1;//declared the integer variable
Random rand = new Random(); //random object
// logic to generate the random numbers between 10 and 99 inclusive
for(int i=0;i<input;i++){
rand_int1 = rand.nextInt(90);
output[i] = rand_int1+10;
}
// returning array of elements
return output;
}
//main method
public static void main(String[] args) {
int input;//input integer variable
int[] output;
//scanner object
Scanner scan = new Scanner(System.in);
System.out.println("How many random 2-digit integers are desired? : ");
//Taking user input for number of random integers
input = scan.nextInt();
scan.close();//scanner closed
//calling the generateRandom to get the random numbers
output = generateRandom(input);
//for each loop to iterate over the array
for (int num : output)
{
//to print the output on the console
System.out.print(num + " ");
}
}
}
Thanks..