In: Computer Science
In java
Modify your finished guessNumber.java program to include a random number generator to generate the guessed number (from 1 to 10). use the Random class to generate a random number between a range of integers. In your program include an if … then statement to check if the number you entered is bigger or smaller than the guessed number, and display a message. Also included is a counter to keep track on how many times the user has guessed, and display it at then end.
Below is the java code that needs to be modified:
/* Week3 in-class exercise
Name: numberGuess.java
Author: Your Name
Date:
*/
// need the Scanner class to get user input
import java.util.Scanner;
public class numberGuess {
/**
* @param args
*/
public static void main(String[] args) {
// TODO:
//
// a. declare a final int, and assign a value of 6 as the guessed
number
final int
guessed_number = 6;
// b. create a Scanner to get user input
Scanner input =
new Scanner(System.in);
// c. use a do {} while loop to prompt the user to enter an integer
between 1 and 10,
// assign the user input to an int, and compare to the guessing
number
int userInput =
0;
do{
System.out.println("Please enter an integer between 1 and
10.");
userInput = input.nextInt();
} while (userInput != guessed_number);
// d. if the number matches the guessed number,
// print out a message that the number entered is correct.
System.out.println("\nNice! You entered the correct
number.\n");
// Here is to print your name
System.out.println("Author: Your Name");
}
}
import java.util.Random;
import java.util.Scanner;
public class GuessNumberRandom {
public static void main(String[] args) {
int cnt=1;
// a. declare a final int, and
assign a value of 6 as the guessed number
Random randomNumbers = new
Random();
final int guessed_number = randomNumbers.nextInt(10);
//b. create a Scanner to get user input
Scanner input = new Scanner(System.in);
//c. use a do {} while loop to prompt the user to
enter an integer between 1 and 10,
//assign the user input to an int, and compare to the
guessing number
int userInput = 0;
do{
System.out.println("Please enter an
integer between 1 and 10.");
userInput = input.nextInt();
if(userInput==guessed_number)
{
System.out.println("\nNice! You entered the correct
number.\n");
break;
}
else
if(userInput>guessed_number)
{
System.out.println("Higher then number");
}
else
if(userInput<guessed_number)
{
System.out.println("lower then number");
}
cnt+=1;
} while (userInput != guessed_number);
System.out.println("total attempt of correct guess is:
"+cnt);
System.out.println("Author: Your Name");
}
}