Question

Every time I call getIndex static method of MyClass prints "Index: 1" to screen. I want to increase or decrease index's value. What is wrong with my code?

public class MyClass 
{
    public static int index=0;

    public static void getIndex()
    {
       index++;
       System.out.println("Index:"+index);
       if(index>10)
            index=0;
    }
}
Was it helpful?

Solution

When I add code to call your example it works as you expect:

public class MyClass 
{
    public static int index=0;

    public static void getIndex()
    {
       index++;
       System.out.println("Index:"+index);
       if(index>10)
            index=0;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 12; i++) {
            getIndex();
        }
    }
}

printing:

Index:1
Index:2
Index:3
Index:4
Index:5
Index:6
Index:7
Index:8
Index:9
Index:10
Index:11
Index:1

to the console. So how you're calling this must be the problem.

OTHER TIPS

A guess: you're calling getIndex() only once in the program, but then running the program several times. That won't work; variable values aren't preserved across instances of the program. Each time you start the program, index is reset to 0. Call getIndex() multiple times within a single run of the program, and you will see it increment as you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top