In: Computer Science
17. Write a program that generates a random number and asks the user to guess what the
number is. If the user’s guess is higher than the random number, the program should display
“Too high, try again.” If the user’s guess is lower than the random number, the program
should display “Too low, try again.” The program should use a loop that repeats until the
user correctly guesses the random number.
18. Enhance the program that you wrote for Programming Challenge 17 so it keeps a count
of the number of guesses that the user makes. When the user correctly guesses the random
number, the program should display the number of guesses.
In Java Programming Please..
Can you please give me unique answer free from plagiarism?
I want varied opinions...
17 code:
import java.util.Scanner;
public class Main {
// Function
public static void findNumber()
{
// Scanner Class
Scanner sc = new Scanner(System.in);
// Generate the random numbers
int random_number = 1 + (int)(100* Math.random());
int guess;
// Iterate until guess number is correct
while(true) {
System.out.println( "Guess the number:");
// input for guessing
guess = sc.nextInt();
// If the number is guessed
if (random_number == guess) {
System.out.println("You guessed the number correctly!");
break;
}
else if (random_number > guess ) {
System.out.println( "Too low, try again.");
}
else if (random_number < guess ) {
System.out.println("Too high, try again.");
}
}
}
public static void main(String arg[])
{
// Function Call
findNumber();
}
}
//screenshot
ouput:
18 QUESTION:
code:
import java.util.Scanner;
public class Main {
// Function
public static void findNumber()
{
// Scanner Class
Scanner sc = new Scanner(System.in);
// Generate the random numbers
int random_number = 1 + (int)(100* Math.random());
int guess;
int count=0;
// Iterate until guess number is correct
while(true) {
count++;
System.out.println( "Guess the number:");
// input for guessing
guess = sc.nextInt();
// If the number is guessed
if (random_number == guess) {
System.out.println("You guessed the number correctly!");
break;
}
else if (random_number > guess ) {
System.out.println( "Too low, try again.");
}
else if (random_number < guess ) {
System.out.println("Too high, try again.");
}
}
System.out.println("Number of guesses : "+count);
}
public static void main(String arg[])
{
// Function Call
findNumber();
}
}
//screenshot
//output:
STEPS:
1.while(true) means the loop is always true and kept break in if condition when that condition is satisfied, the loop will break
2.count is 0 initially, it is used to count the number of guesses in the program