Stefan Carlson
Stefan Carlson

Reputation: 372

Accessing value of local variable for an instance variable in java

I looked this up but didn't find much. Here's the code:

    public class Core {
        int amount = 0;
        public void startup(int Items) {
            int x = 0;
            System.out.println("Welcome Back,");
            while(x < amount) {
                amount++;
                x++;
            }
        }
        agendaitem[] item = new agendaitem[150];
        public void instantiate(String name, String status, String comments,int i) {
            item[i] = new agendaitem();
            item[i].name = name;
            item[i].complete = status;
            item[i].comments = comments;
        }
        public void error(String reason) {
            System.out.println("Error"+reason);
        }
        public void setitem(String input) throws Exception {
            Interface interf = new Interface();
            System.out.println(amount);
            int x = 0;
            while(x < amount) {
                interf.inputb(item[amount].name);
                break;
            }
        }
        public void setstatus() {

        }
        public void rename() {

        }
        public void delete() {

        }
    }

Basically I need to set the value of the variable amount so that it is the same as the value of Items from the method startup. Then i need to access amount from the method setitem. But for whatever reason, setitem sees amount as 0, even after i have set the value to 2 by running startup. Any advice? Thanks. :)

Upvotes: 0

Views: 94

Answers (3)

Davie Brown
Davie Brown

Reputation: 717

I think what you could be looking for is to make "amount" a static variable in your Core class. This would involve declaring it as follows:

static int amount = 0;

See here for info : http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

Inside the loop inside startup, you're incrementing both x and amount. So if x < amount, then it will always be the case that x < amount - at least until amount reaches MAXINT.

I strongly recommend learning to use the debugger. You would have found this error immediately.

Upvotes: 1

ssantos
ssantos

Reputation: 16526

while(x < amount)

will return false, since both x and amount are 0 at the beginning, so amount will always keep 0 value. Why not just doing

amount = items

?

Your startup method would look like this.-

public void startup(int Items) {
    amount = Items;
}

By the way, following java naming conventions, Items should be called items, camelCase.

Upvotes: 0

Related Questions