-4

I am trying to build a guessing game for an assignment I am currently working on using loops. I am trying to get my game to give the user the option to play again. I was having a hard time trying to set up this last bit of code so I followed an example on youtube. Although I have declared the variable restart the compiler keeps telling me I have not initialized it. Any help with this code would be appreciated

import java.util.Scanner;
import java.util.Random;

public class High_Low_Game {

    public static void main (String[] args){


    Random rand=new Random();
    Scanner scan= new Scanner(System.in);
    int guess,num,count=0;
    String restart;

    num=rand.nextInt(99+1);
    do{

    System.out.println("Please enter a number from 1-100,press 0 to quit");
    guess=scan.nextInt();
    count++;
    while(guess!=0)
        if(guess>num){

           System.out.println("Your guess was too high, try again");
           guess=scan.nextInt();
           count++;}
        else

         if(guess<num){
           System.out.println("The number is too low,enter another guess ");
           guess=scan.nextInt();
           count++;}
       else
        if(guess==num){
            System.out.println("You have guessed correctly");
            System.out.println("It took you "+count+ " guesses");
            System.out.println("Would you like to play again? (Y/N)");
            restart=scan.next();}
     }while(restart.equals("Y"));

    }            
   }
Andreas
  • 154,647
  • 11
  • 152
  • 247

2 Answers2

1

It's indicating that the variable hasn't been initialized because it's only ever intialized if guess is == num.

Jason
  • 5,154
  • 2
  • 12
  • 22
0

If You need a detailed answer for this simple thing read this

Unlike member variables local variables don't get a default value at the time of class loading.

Class loading is a run time thing in java means when you create an object then the class is loaded with class loading only member variables are initialized with default value JVM does not take time to give default value to your local variables because some methods will never be called because method call can be conditional so why take time to give them default value and reduce performance if those defaults are never going to be used.

In you case restart is local variable of main method so it does not get a default value and if you come from C, C++ background you tend to think it could contain garbage value but there is no such thing in java.

when guess == num is false then in while restart.equals("Y")restart contains nothing

So in short before using , your variable should have some value.

Abhinav Chauhan
  • 1,304
  • 1
  • 7
  • 24