In: Computer Science
Write a program in java which randomly generates two integer number n1 and n2 (suppose the range for each integer is [1, 100]), then asks the user what is the value of n1*n2, if the user’s answer is correct, call method printGoodComment to print out something nice, otherwise, call printBadComment to print out something “mean”.
The method signatures are:
public static void printGoodComment()
and
public static void printBadComment()
in your printGoodComment method, it will randomly print one sentence from the following lists:
good job
excellent
terrific
nice work
in your printBadComment method, it will randomly print one sentence from the following lists:
sorry, try next time
oops, you need more work
hmm, it is not correct
Hint: use Math.random and a switch statement in the printGoodComment and printBadComment methods.
The solution to the above question is:-
code for above program is:-
import java.util.*;
import java.lang.Math; //used to import Math library.
class Random //name of the class.
{
public static void main(String args[])
{
Scanner sc = new
Scanner(System.in); //object used for taking input.
int max=100; // maximum number for
generation of the random number.
int min=1; // minimum number for
generation of the random number.
int range = max-min+1; // range
which is used for generating random numbers between the max and min
terms.
int n1 =
(int)(Math.random()*range)+min; // generating the 1st random
number.
int n2
=(int)(Math.random()*range)+min; // generating the 2nd random
number.
//System.out.println("rand
1:"+n1);
//System.out.println("rand
2:"+n2);
System.out.println("Enter your
guess answer:");
int guess = sc.nextInt(); // taking
the guess from the user.
if(guess == n1*n2) // checking the
condition wheather your guess is correct or not.
{
printGoodComment(); // if guess is correct calling
printGoodComment() method.
}
else
{
printBadComment(); // if guess is wrong calling printBadComment()
method.
}
}
public static void printGoodComment()
{
int min=0; // defining minimum
range
int max=3; // defining maximum
range.
int range = max-min+1; // taking
range.
int n1=
(int)(Math.random()*range)+min; // generating random number within
the range.
switch(n1) //using switch to
generate the output randomly.
{
case 0:
System.out.println("good job");
break;
case 1:
System.out.println("Excellent");
break;
case 2:
System.out.println("terrific");
break;
case 3:
System.out.println("nice work");
break;
}
}
public static void printBadComment()
{
int min=0;
// defining the minimum
range.
int max=2;
// defining the maximum
range.
int range = max-min+1;
// setting the range.
int n1=
(int)(Math.random()*range)+min; // generating the random
number.
switch(n1) // using the switch to
generate output.
{
case 0:
System.out.println("sorry,try next time
");
break;
case 1:
System.out.println("oops,you need more
work");
break;
case 2:
System.out.println("hmm, it is not
correct");
break;
}
}
}
output for above code is:-
Thank you.