Acceso al valor de la variable local para una variable de instancia en 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. :)

preguntado el 09 de septiembre de 13 a las 21:09

3 Respuestas

Inside the loop inside startup, you're incrementing both x y amount. Así que si x < amount, then it will always be the case that x < amount - at least until amount alcances MAXINT.

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

Respondido el 09 de Septiembre de 13 a las 21:09

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

Respondido el 09 de Septiembre de 13 a las 21:09

while(x < amount)

regresará false, ya que ambos x y amount are 0 at the beginning, so amount will always keep 0 value. Why not just doing

amount = items

?

Su startup method would look like this.-

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

By the way, following java naming conventions, Items debería llamarse items, camelCase.

Respondido el 09 de Septiembre de 13 a las 21:09

I had it like that originally, but it didn't work so tried just incrementing amount until was equal to items - Stefan Carlson

Have you tried debugging your code? Are you accidentally creating more than one instance of Core ¿clase? - santos

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.