Development java game help!

Discussion in 'Software' started by brighty22, 30 Sep 2010.

  1. brighty22

    brighty22 What's a Dremel?

    Joined:
    19 Aug 2010
    Posts:
    178
    Likes Received:
    5
    I started my computer science ib 3 weeks ago, and have been asked to create a simple game where a random number is chosen by the program, and the user has 5 chances to guess the number.

    I've got a problem with the 'sorry, you lost' bit... I need to show a percentage error of how far out the user was. g3 is the number the player guessed on their final chance.

    Code:
    else {
        int pce;
        if (g3>number) {
            pce = (((g3-number)/g3)*100);
        }
        if (g3<number) {
            pce = (((number-g3)/number)*100);
        }
        System.out.println("No: the number was "+number+". Unlucky, you were only "+pce+"% out!");
    }
    BlueJ highlights the second last line, saying variable pce hasn't been initialised... any ideas why? :wallbash:

    I can post the rest of the code (108 lines) if it would help :)

    Thanks :thumb:
     
  2. capnPedro

    capnPedro Hacker. Maker. Engineer.

    Joined:
    11 Apr 2007
    Posts:
    4,381
    Likes Received:
    241
    Try changing int pce; to
    Code:
    int pce = 0;
     
    thehippoz likes this.
  3. brighty22

    brighty22 What's a Dremel?

    Joined:
    19 Aug 2010
    Posts:
    178
    Likes Received:
    5
    genius :thumb: but why do you have to give it a value for it to be initialised? (just so I understand for next time :))
     
  4. capnPedro

    capnPedro Hacker. Maker. Engineer.

    Joined:
    11 Apr 2007
    Posts:
    4,381
    Likes Received:
    241
    It's been a long time since I did any Java, but if I remember correctly, you have to initialise all local primitive data types like that because the compiler doesn't assign them an initial value.
     
  5. JazzXP

    JazzXP Eh! Steve

    Joined:
    30 Apr 2002
    Posts:
    1,669
    Likes Received:
    13
    This. Local variables have to be initialised, class variables get default values (typically 0 or null depending if it's a primitive or an object)
     
  6. brighty22

    brighty22 What's a Dremel?

    Joined:
    19 Aug 2010
    Posts:
    178
    Likes Received:
    5
    right, thanks to you both :)
     

Share This Page