Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: problem with enum in my coin toss program.

  1. #1
    Azaera is offline Member
    Join Date
    Jun 2012
    Location
    Gothenburg, Sweden
    Posts
    5
    Rep Power
    0

    Default problem with enum in my coin toss program.

    Hello all. Newbie that tries to get java in the head and usually manages to find solutions but this time I didnt so I hope for some help in right direction so I can get it to work.
    I still can't figure out why I get the error "gameStatus might not be initilized", because when I skip the if statements, the program runs perfect and the variable gameStatus gets initlized.

    Java Code:
    /*
    (Coin Tossing) Write an application that simulates coin tossing. 
    Let the program toss a coin
    each time the user chooses the “Toss Coin” menu option. 
    Count the number of times each side of
    the coin appears. Display the results. 
    The program should call a separate method flip that takes no
    arguments and returns a value from a Coin enum (HEADS and TAILS). 
    [Note: If the program realistically
    simulates coin tossing, 
    each side of the coin should appear approximately half the time.]
    */
    import java.util.*;
    
    public class CoinToss
    {
    	private enum Coin { HEADS, TAILS };
    	
    	private static final Random randomNumbers = new Random();
    	
    	private static final int HEAD = 1;
    	private static final int TAIL = 2;
    	
    	public static void main(String[] args)
    	{
    		Scanner input = new Scanner( System.in );
    		
    		int choice;
    		int toss = 0;
    		int tosses = 0;
    		int frontflip = 0;
    		int backflip = 0;
    		
    		Coin gameStatus;
    		
    		System.out.println("Welcome to the Coin Toss Program.\n");
    		System.out.println("Choose from the menu what you want to do.");
    		System.out.print("1. Toss the coin\n2. Quit program\n");
    		choice = input.nextInt();
    		
    		while ( choice != 0 )
    		{
    			if ( choice == 1 )
    			{
    				int CoinTossed = Flip();
    				
    				switch ( CoinTossed )
    				{
    				case HEAD:
    					gameStatus = Coin.HEADS;
    					System.out.println("GameStatus: " + gameStatus); // To verify gameStatus gets initilized
    					break;
    				case TAIL:
    					gameStatus = Coin.TAILS;
    					System.out.println("GameStatus: " + gameStatus); // To verify gameStatus gets initilized
    					break;
    				}
    				
    				if ( gameStatus == Coin.HEADS )
    				{
    					frontflip++; //Add amount of heads
    					tosses++;   //Add amount of tosses
    				}
    				else // gameStatus == TAILS
    					backflip++; //Add amount of tails
    					tosses++;   //Add amount of tosses		
    			}
    			
    			// A try to make an real exit out of a program
    			
    			if ( choice == 2 )
    			{
    				EndProgram( frontflip, backflip, tosses );
    			}
    			
    			System.out.println("\nChoose from the menu what you want to do.");
    			System.out.print("1. Toss the coin\n2. Quit program\n");
    			choice = input.nextInt();	
    		}	
    	}
    	
    	//Toss the coin to determine 1 or 2.
    	public static int Flip()
    	{
    		int toss;
    		
    		toss = 1 + randomNumbers.nextInt( 2 );
    		
    		if ( toss == 1 )
    		{
    			System.out.println("You toss the coin and it lands on head!");
    		}
    		else
    		{
    			System.out.println("You toss the coin and it lands on tails!");
    		}
    		return toss;
    	}
    	
    	public static void EndProgram( int frontflip, int backflip, int tosses )
    	{
    		System.out.printf("You have tossed %d times.\n", tosses);
    		System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
    		System.exit(0);
    	}
    }

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: problem with enum in my coin toss program.

    I still can't figure out why I get the error "gameStatus might not be initilized",
    The compiler will complain if you use the variable gameStatus - as you do in the condition part of the nested if statement - when that variable might not have been assigned a value. The point is that the two branches of the switch statement may or may not cover every case and assign some value to the variable: the compiler is not going to check that. The compiler will be happy if the switch contains a "default" part initialising the variable, but not otherwise. Additionally it wants to see an assignment in every path through the switch that can "break" out.

    (The exact rules are mentioned in the Java Language Specification 4.12.5) where we learn "Every variable in a program must have a value before its value is used" ... "A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16)." But, beware! chapter 16 is pretty much devoted to devoted to precisely defining what is meant by saying something is "definitely assigned" - for most of us it is enough to recognise that the compiler will grumble unless the "default" path is there or gameStatus assigned a value before the switch statement.)

    The same ("assign before the switch or in a default path and every path through the switch that breaks") applies even when the Java language enum type is used (if I remember correctly) and is certainly the case where you declare static final primitives to play the role of enumerated values.

    when I skip the if statements, the program runs perfect and the variable gameStatus gets initlized.
    It's hard to comment on that without the code.

    As posted, if you comment out the innermost nested if statement then the value of gameStatus is never used. And so the compiler will have no cause to grumble about it not being definitely assigned (in the sense of Chapter 16).

    I guess the bottom line is that what matters is not whether a variable is assigned - even that it always and necessarily is assigned: but, rather, that it is assigned in an "obvious" way that conforms to the compiler's demand that it be checkable by its rather cursory - but precisely defined - procedures.
    Last edited by pbrockway2; 06-21-2012 at 12:05 AM.
    Azaera likes this.

  3. #3
    Azaera is offline Member
    Join Date
    Jun 2012
    Location
    Gothenburg, Sweden
    Posts
    5
    Rep Power
    0

    Default Re: problem with enum in my coin toss program.

    Thank you very much.
    After some tweaking in the code, made it work as I wanted, and I can finally rest on this one.

  4. #4
    Tha Boss is offline Member
    Join Date
    Jun 2012
    Location
    ON, Canada.
    Posts
    25
    Rep Power
    0

    Default Re: problem with enum in my coin toss program.

    "Ready" couldn't run your program ...So I'll try to make as best judgement as I can based on what I see...
    Hmm.. look at your code, you initialized tosses, frontflip, and backflip by setting their initial value = 0. But you just declared coin gameStatus and use it in if statements.. your compiler will always "grumble" when it sees this, as it looks for a "Definite" value in variables before it's first used.
    I think simply saying coin gamestatus = null; at the starting should fix this problem.
    Also, you code has a few logic errors that could mess up your calculation at the end. (*HINT* check how you used your while and else statements).
    - CHEERS!

    "No human is perfect... our flaws mean that we're functioning perfectly."
    - Jimmy Neutron.

    E.Hughes
    "I'm sometimes hard to please... because I'm only satisfied with the very best." - Fernand Point.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: problem with enum in my coin toss program.

    Quote Originally Posted by Azaera View Post
    Thank you very much.
    After some tweaking in the code, made it work as I wanted, and I can finally rest on this one.
    You're welcome.

    You don't say *how* you tweaked, but since Tha Boss mentions putting "gameStatus=null" before the switch statement, I'll mention my prejudice *against* this way of doing things.

    The compiler's error is alerting you to a problem and it's a case of fixing the problem - not fixing the compiler by keeping it quiet! The problem (when you get a "foo may not be initialised") is usually that the code has become too complex and convolved. The solution is to look for ways of simplifying it: fewer variables, declared close to where they are being used.

    I'm thinking along the lines of

    Java Code:
    if(choice == 1) {
        tosses++;
        if(flip() == Coin.HEADS) {
            frontFlip++;
        } else {
            backFlip++;
        }
    } else 
      // etc
    No danger of accessing an uninitialised variable if you don't declare or use the variable at all!

    Hope this gives you something to think about as you test and debug.

  6. #6
    Azaera is offline Member
    Join Date
    Jun 2012
    Location
    Gothenburg, Sweden
    Posts
    5
    Rep Power
    0

    Default Re: problem with enum in my coin toss program.

    Well, maybe Tha Boss version with a null also works, but I solved it like this, and I think I found the logical error he meant as my amount of tosses could skyrocket compared to amount of tosses I actually did, but solved it by moving the increment into the switch statement (actually just by a try to do it) and now reading more about nested switch - if statements to understand better why the increment didn't work right before.

    Java Code:
    /*
    (Coin Tossing) Write an application that simulates coin tossing. 
    Let the program toss a coin
    each time the user chooses the “Toss Coin” menu option. 
    Count the number of times each side of
    the coin appears. Display the results. 
    The program should call a separate method flip that takes no
    arguments and returns a value from a Coin enum (HEADS and TAILS). 
    [Note: If the program realistically
    simulates coin tossing, 
    each side of the coin should appear approximately half the time.]
    */
    import java.util.*;
    
    public class CoinToss
    {
    	private enum Coin { HEADS, TAILS };
    	
    	private static final Random randomNumbers = new Random();
    	
    	private static final int HEAD = 1;
    	private static final int TAIL = 2;
    	
    	public static void main(String[] args)
    	{
    		Scanner input = new Scanner( System.in );
    		
    		int choice;
    		int toss = 0;
    		int tosses = 0;
    		int frontflip = 0;
    		int backflip = 0;
    		
    		Coin gameStatus;
    		
    		System.out.println("Welcome to the Coin Toss Program.\n");
    		System.out.println("Choose from the menu what you want to do.");
    		System.out.print("1. Toss the coin\n2. Quit program\n");
    		choice = input.nextInt();
    		
    		while ( choice != 0 )
    		{
    			if ( choice == 1 )
    			{
    				int CoinTossed = Flip();
    				
    				switch ( CoinTossed )
    				{
                                    //added tosses to switch statement to make the counter work perfect.
    				case HEAD:
    					gameStatus = Coin.HEADS;
    					tosses++; // add amount of tosses
    					break;
    				default: // changed case TAIL to default. Easy and works.
    					gameStatus = Coin.TAILS;
    					tosses++; // add amount of tosses
    					break;
    				}
    				
    				if ( gameStatus == Coin.HEADS )
    				{
    					frontflip++; //Add amount of heads
    				}
    				else // gameStatus == TAILS
    					backflip++; //Add amount of tails		
    			}
    			
    			// A try to make an real exit out of a program
    			
    			if ( choice == 2 )
    			{
    				EndProgram( frontflip, backflip, tosses );
    			}
    			
    			System.out.println("\nChoose from the menu what you want to do.");
    			System.out.print("1. Toss the coin\n2. Quit program\n");
    			choice = input.nextInt();	
    		}	
    	}
    	
    	//Toss the coin to determine 1 or 2.
    	public static int Flip()
    	{
    		int toss;
    		
    		toss = 1 + randomNumbers.nextInt( 2 );
    		
    		if ( toss == 1 )
    		{
    			System.out.println("You toss the coin and it lands on head!");
    		}
    		else
    		{
    			System.out.println("You toss the coin and it lands on tail!");
    		}
    		return toss;
    	}
    	
    	public static void EndProgram( int frontflip, int backflip, int tosses )
    	{
    		System.out.printf("You have tossed %d times.\n", tosses);
    		System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
    		System.exit(0);
    	}
    }
    Think this is somewhat good solution, but 100% confident I will be able to improve on it as I learn more.
    Thank you for the help :)
    Very appreciated.

Similar Threads

  1. Replies: 7
    Last Post: 10-31-2011, 01:05 AM
  2. help with my coin toss program please?
    By tran21 in forum New To Java
    Replies: 6
    Last Post: 10-30-2011, 05:20 AM
  3. Trying to finish coin toss project
    By learn in forum New To Java
    Replies: 2
    Last Post: 10-29-2011, 11:54 PM
  4. coin flip program
    By chandrasekhar.melam in forum New To Java
    Replies: 5
    Last Post: 09-26-2011, 05:30 PM
  5. coin toss program(Eclipse)
    By ccie007 in forum New To Java
    Replies: 5
    Last Post: 08-06-2010, 07:03 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •