Page 121 - CTS - CSA TP - Volume 2
P. 121
COMPUTER SOFTWARE APPLICATION - CITS
Explanation:
• In this program, we define a method findMax that takes two integers as parameters and returns the maximum
of the two.
• We declare variables a and b in the main method and assign values to them.
• We call the findMax method and pass a and b as arguments.
• Inside the findMax method, we use the ternary operator to determine the maximum of the two integers.
• The maximum value is returned and stored in the max variable in the main method.
• Finally, we print the maximum value to the console.
TASK 2: Generating a Random Number
import java.util.Random;
public class RandomNumberDemo {
public static void main(String[] args) {
// Calling the method to generate a random number
int randomNumber = generateRandomNumber();
System.out.println(“Generated random number: “ + randomNumber);
}
// Method to generate a random number
public static int generateRandomNumber() {
Random random = new Random();
return random.nextInt(100); // Generates a random number between 0 and 99
}
}
Output:
Explanation:
• In this program, we import the Random class from the java.util package to generate random numbers.
• We define a method generateRandomNumber that returns a randomly generated integer.
• Inside the generateRandomNumber method, we create an instance of the Random class and use its nextInt
method to generate a random integer between 0 and 99.
• The generated random number is returned to the main method, where it is stored in the randomNumber
variable.
• Finally, we print the generated random number to the console.
106
CITS : IT & ITES - Computer Software Application - Exercise 96