Guessing Game

/** * Charlotte Weisman * B Block CompSci * Sep 12, 2017 * Guessing Game */ import java.util.*; public class guessingGame { public static void main(String args[]){ Scanner sc = new Scanner(System.in); //scanner Random rand = new Random(); //to get a random number boolean keepGoing = true; //for while loop, to repeat program if playing again while(keepGoing) { System.out.println("Please guess a number between 1 and 10:"); int firstGuess = sc.nextInt(); //user's first guess int rnd = rand.nextInt(10) + 1; //number trying to guess if (firstGuess==rnd){ //compare random number and user guess System.out.println("Your guess:" + firstGuess + " My number:" + rnd); System.out.println("You win!"); }else{ //if they get it wrong System.out.println("Sorry, wrong. Guess again:"); int secondGuess = sc.nextInt(); //program repeats if they get it wrong up to 2 more times if (secondGuess==rnd){ System.out.println("Your guess:" + secondGuess + " My number:" + rnd); System.out.println("You win!"); }else{ System.out.println("Sorry, wrong. Guess again:"); int thirdGuess = sc.nextInt(); if (thirdGuess==rnd){ System.out.println("Your guess:" + thirdGuess + "My number:" + rnd); System.out.println("You win!"); }else{ System.out.println("Sorry, wrong. The number was:" + rnd + " You lose!"); //if they get it wrong, reveal the number } } }System.out.println("Press 1 to play again. Press any other number to quit."); //1 makes the boolean true, repeating the program int cont = sc.nextInt(); if(cont !=1){ keepGoing = false; System.out.println("Thanks for playing!"); } } }}
Guessing Game for AP Comp Sci

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.