Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A guessing game (implemented with a recursive function) The goal of this project

ID: 3649705 • Letter: A

Question

A guessing game

(implemented with a recursive function)

The goal of this project is to apply recursivity in the implementation of a guessing game.

The game rules are the following:

1. The computer generates a random integer R between 1 and 9

2. The user tries to guess the number, by entering numbers again and again until eventually the user enters R

3. The user can give up at any time by entering the number 0

The implementation must obey a few rules:

1. Everything will be implemented in one Java file YourNamePrj2.java; it is a console application, no graphics here.

2. The main method will generate the number R, then it will call a recursive method that will ask the user for numbers until the game stops.

3. According to the rules above, the game can only stop in two situations:

- either the user gives up, by entering 0, in which case the message "You gave up! Computer wins!" is displayed

- or the number R is eventually entered by the user, and the message: "You won after X attempts!" is displayed (where X is the actual number of attempts of guessing the number R)

4. Let the recursive method be called "guess". This will be the only method of the class except for the "main" method.

Explanation / Answer

import java.util.Random; import java.util.Scanner; public class Help { static String rand; static Scanner in = new Scanner(System.in); static int count = 0; public static void guess(){ System.out.println("Enter your guess."); String g = in.nextLine(); count++; if(g.equals(rand)){ System.out.println("You won after " + count + " attempts."); } else if(g.equals("0")){ System.out.println("You Gave Up! The Computer Wins!"); } else{ guess(); } } public static void main(String[] args){ Random r = new Random(); rand = "" + (r.nextInt(9) + 1); guess(); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote