lundi 29 octobre 2018

Mystery Number Game (Java)

I want the computer to choose a random number between 1 and 100 and then the user will repeatedly guess until they guess correctly.

Example I'm thinking of a number between 1-100. Can you guess it? Guess # 1: 50 Sorry, you are too low. Guess # 2: 75 Sorry, you are too low. Guess # 3: 87 Sorry, that guess is too high. Guess # 4: 82 Sorry, you are too low. Guess # 5: 84 You guessed it!

My code seems to generate an extra guess for some reason, how can I make it generate the right amount of guesses?

Here is my code:

import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);

  System.out.println("Enter a seed for the random number generator:");
  int seed = scnr.nextInt(); 
  Random random = new Random(seed);
  int compNum = (int)(Math.random()*100) + 1;
  int numGuess=1;
  int userGuess=-1;

  System.out.println();

  System.out.println("I'm thinking of a number between 1-100. Can you guess it? ");

  do {
  System.out.println("Guess " + "# " + numGuess);
  userGuess = scnr.nextInt();

  if (compNum > userGuess) {
  System.out.println("Sorry, you are too low.");


  }
  else if (compNum < userGuess) {
  System.out.println("Sorry, that guess is too high.");

  }
  else if (compNum==userGuess) {
     System.out.println("You guessed it! ");
  }

  ++numGuess;

  }while (compNum!=userGuess) ;
   }
}




Aucun commentaire:

Enregistrer un commentaire