|
Java: Cumulative Sum and While Loop
For my assignment i am supposed to create a guessing game and I did, and it works but then also count the number of guesses the user has tried and that works BUT when I tried to do a total sum of the # of guesses of all the game the user plays, it doesn't work?
import java.util.*;
public class GuessingGame {
public static final String Y = "Y";
public static final String y = "y";
public static void main(String[] args) {
//main game
game();
}
//while loop for guessing
public static void game() {
Random rand = new Random();
Scanner console = new Scanner(System.in);
int randomNumber = rand.nextInt(1);
int generate = 0;
int tries = 1;
int totalGames = 0;
while (generate == 0){
System.out.println("I'm thinking of a number between 1 and 100...");
System.out.print("Your guess? ");
int guess = console.nextInt();
if(guess < randomNumber){
System.out.println("It's higher. ");
tries++;
}
if(guess > randomNumber){
System.out.println("It's lower. ");
tries++;
}
if(guess == randomNumber){
if ( tries == 1){
System.out.println("You got it right in 1 guess!");
}else if (tries > 1) {
System.out.println("You got it right in " +tries +" guesses!");
generate = 0;
}
System.out.print("Do you want to play again? ");
String word = console.next();
if (word.startsWith(Y)) {
game();
}
if (word.startsWith(y)) {
game();
}else if (!word.equals(Y)) {
totalGames++;
System.out.println("Total games = " +totalGames);
System.out.println("Total guesses =" +totalGames*tries);
word = console.next();
}
}
}
}
}
|