Java Variable Help?

Front Page Forums MCNSA Java Variable Help?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #249
    quantumkitty
    Participant

    So, i’m rather confused. i know how to initialize variables and, for the most part, use them.
    The problem for me, however, is when I attempt to use said variables in a different class in the project. For example, I would have a variable called “Health” in one class. An event in an outside class, like the use of specific potion would increase the health, but I do not know how to change variables through classes.

    I’ve tried to fix it through experimentation, such as using “public int Health = 0;” but, as i’ve long ago realized… It don’t do shit.

    Anyone willing to give me a short tutorial on using one variable in multiple classes?
    even the java bible hasn’t helped me one bit D:

    #3106
    quantumkitty
    Participant

    oh, right, and as i do remember the rules:

    boolean kickedmicro = false;

    while(kickedmicro == false)
    {
    System.out.println("quick, kick micro!");
    if (kickedmicro == false)
    {
    Kick("Microsoftt");
    kickedmicro = true;
    }
    else
    {
    System.out.println("how are you even in this loop then? o.o");
    }
    }
    #3107
    quantumkitty
    Participant

    ignore mah choppy and completely wrong coding 😀

    #3108
    Kenix
    Member

    I think what you are looking for is either making it public or encapsulate it with setter and getter methods. Using encapsulation is recommended but both methods will work.

    Try read section 5.1.3 of this article

    Made an example for you to get the idea,

    public class MyClass {
    private int privateHealth = 0;
    public int publicHealth = 0;

    // Sets the value private health
    public void setPrivateHealth( int newHealth ) {
    privateHealth = newHealth ;
    }

    // Gets the private health value
    public int getPrivateHealth () {
    return privateHealth ;
    }


    public static void main(String[] args) {

    // Initialize new instance of myClass
    MyClass myClass = new MyClass();

    //Test the private health setters and getters
    System.out.println(myClass.getPrivateHealth ());
    myClass.setPrivateHealth(5);
    System.out.println(myClass.getPrivateHealth ());

    //Test the public health
    System.out.println(myClass.publicHealth);
    myClass.publicHealth = 3;
    System.out.println(myClass.publicHealth);
    }
    }

    // --- Starting Execution ---
    // 0
    // 5
    // 0
    // 3
    // --- Finished Execution Normally ---
    #3109
    quantumkitty
    Participant

    Ah, thank you very much XD
    i think i could understand it with just the example you gave, but the article should help a lot 😀

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.