In: Computer Science
Write a JAVA program that generates three random numbers from 1 to 6, simulating a role of three dice. It will then add, subtract and multiply these two numbers. It will also take the first number to the power of the second and that result to the power of the third. Display the results for each calculation. Please note that the sample run is based on randomly generated numbers so your results will be different.
Sample run:
6 + 2 + 5 = 13
6 - 2 – 5 = -1
6 * 2 * 5 = 60
6 to the power of 2 to the power of 5 = 60,466,176
A second sample run:
2 + 3 + 5 = 10
2 – 3 - 5 = -6
2 * 3 * 5 = 30
2 to the power of 3 to the power of 5 = 32,768
Program code to copy:-
import java.util.Random;
import java.lang.Math;
public class RandomNumbersMath
{
/**
* This program will generates three random numbers from 1 to 6.
* It will then add, subtract and multiply these numbers.
* It will also take the first number to the power of the second and that result to the power of the third.
* Display the results for each calculation.
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] num = new int[3]; // Declaring array of 3 integer
Random r = new Random(); //Creating an object of random class
for (int i = 0; i < 3; i++)
num[i] = r.nextInt(6)+1; // storing random integer number in an array
int add = num[0] + num[1] + num[2] ; //adding the numbers
int sub = num[0] - num[1] - num[2] ; //Subtracting the numbers
int mul = num[0] * num[1] * num[2] ; //Multiply the numbers
//Calculate the first number to the power of the second and that result to the power of the third.
//By default Math.pow() function returns double type so casting is done to convert double into int
int power = (int) Math.pow(Math.pow(num[0], num[1]), num[2]);
//Printing desired output of calculation done for add, subtract and multiply
System.out.println(num[0] + " + " + num[1] + " + " + num[2] + " = " + add);
System.out.println(num[0] + " - " + num[1] + " - " + num[2] + " = " + sub);
System.out.println(num[0] + " * " + num[1] + " * " + num[2] + " = " + mul);
//Printing power of numbers with thousand separator by using String.format() function
System.out.println(num[0] + " to the power of " + num[1] + " to the power of " + num[2] + " = " + String.format("%,d", power));
}
}
Sample output:-