Untitled
unknown
plain_text
2 years ago
2.7 kB
3
Indexable
Never
import java.util.Scanner; public class Main { final static int maxNumber=50; static Scanner scanner = new Scanner(System.in); static int contGuess = 0; static int fewestGuess; static String option = "Y"; static int numberPlayGames = 0; static int totalGuesses = 0; public static void initGame(){ System.out.println("This program allows you to play a guessing game.\n"+ "It will think of a number between 1 and 100\n "+ "and will allow you to guess until you get the number.\n" + "For each guess, it will tell you whether you have\n"+ "guessed too high or too low\n"); } public static void statistics(){ System.out.println("Game Statistics"); System.out.println("Games: "+numberPlayGames); System.out.println("Guesses: "+totalGuesses); System.out.println("Guesses/Games: "+(float) totalGuesses/numberPlayGames); System.out.println("Fewest guesses: "+fewestGuess); } public static void playGame(){ contGuess = 0; numberPlayGames += 1; int numberToGuess = (int) (Math.random()*maxNumber+1); System.out.println("I'm thinking of a number between 1 and 100..."); do { System.out.println("Your guess?"); int myNumber = scanner.nextInt(); contGuess += 1; totalGuesses += 1; if ( numberToGuess == myNumber){ if (contGuess == 1) System.out.println("You got it right on the first guess!"); else System.out.printf("You got it right in %d guesses\n",contGuess); if ( numberPlayGames == 1){ fewestGuess = contGuess; }else { if (contGuess < fewestGuess) fewestGuess = contGuess; } System.out.print("Do you want to play again?"); option = scanner.next(); if (option.toLowerCase().charAt(0) == 'y'){ playGame(); }else{ statistics(); } }else { if (myNumber>numberToGuess){ System.out.println("Too high"); }else{ System.out.println("Too low"); } } }while(option.toLowerCase().charAt(0) == 'y'); } public static void main(String args[]) { initGame(); playGame(); } }