0

I'm making a little text game. The starting dialogue is in my main (static) method. From there, it sends you to other methods depending on your choices.

Now I think I need to have an instance of my class for this to work.

For example:

Program p = new Program();

if(stuff){
    p.room1();
}
else{
    p.room2();
}

Within those other methods there are global variables that will change.

So above the main method there is:

public bool hasItem = false;

So room1() would look like,

public void room1(){
    if(stuff){
        p.hasItem = true;
    } 
}

I know I'm screwing something up with the main method. Do I declare the instance "p" inside or outside of the main method? I've tried both but get errors both ways.

Edit: I ended up declaring a static "Program" outside of the main method to use elsewhere. Thanks for the help!

2
  • 1
    I am not following your question at all. Is the issue is that you don't know where to declare hasItem? I would suggest you declare it as a member variable of the object that represents the thing (room, world, player, whatever) that actually has the item. Commented Jan 10, 2017 at 23:19
  • I thought that's what I did by declaring it outside of a method. Is that not the case? Commented Jan 10, 2017 at 23:21

1 Answer 1

2

First off, you can either create a static Program outside of your main method, or declare a program inside your main method, depending on your architecture.

Second, you don't have to reference your instance from within your instance methods. Just use the field name. like so:

public void room1(){
    if(stuff){
        hasItem = true;
    } 
}

you can use this.hasItem if you want to be explicit about it.


Or better yet, make a brand new class to keep your state in. Having instance members in the class with the main method is awkward design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.