Guessing My Number File Guessing.java contains a skeleton of a program that play
ID: 670807 • Letter: G
Question
Guessing My Number
File Guessing.java contains a skeleton of a program that plays a simple guessing game with the user. Using the comments as a guide, complete the program so that it prints out the result of the guessing.
//*******************************************************************
// Guessing.java
//
//*******************************************************************
import java.util.*;
public class Guessing
{
//-----------------------------------------------------------------
// Plays a simple guessing game with the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MAX = 10;
int answer, guess;
Scanner scan = new Scanner (System.in);
Random generator = new Random();
// create a random number between 1 and MAX and store it in answer
System.out.print ("I'm thinking of a number between 1 and "
+ MAX + ". Guess what it is: ");
guess = scan.nextInt();
// complete the while loop so that the program will keep
// asking the user to try again until the user’s guess
// is correct
while( ){
//print the message your guess is not correct
// ask the user the try again and read in the number
}
System.out.println ("You got it! Good guessing!");
}
}
Explanation / Answer
import java.util.*;
public class GuessingGame{
public static void main(String args[]){
Random rand = new Random();
int numberToGuess = rand.nextInt(1000);
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while(win == false){
System.out.println("Guess a number between 1 and 1000:");
guess = input.nextInt();
numberOfTries++'
if(guess==numberToGuess){
win=true;
}
else if(guess<numberToGuess){
System.out.println("Your guess is too low");
}
else if(guess >numberToGuess){
System.out.println("Your guess is too high");
}
}
System.out.println("You win!");
System.out.println("The number was"+numberToGuess);
System.out.println("It took you"+numberOfTries+"tries");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.