0

I want the variable called "number" to stay the same value when the method is called multiple times. It seems like it resets between each method call. I don't see why it would because the variable is declared outside the method.

This is the first class:

import java.util.Scanner;

public class Input {

    public static void main(String[] args) {

        for(int counter = 0; counter < 5; counter++) {
            Output display = new Output();
            display.outputNumber();
        }

    }

}

This is the second class:

public class Output {

    int number;

    public void outputNumber() {
        number++;
        System.out.println(number);
    }

}

When I run this, it outputs

1
1
1
1
1

I want it to output:

1
2
3
4
5
1
  • 2
    Then don't create a new Output object at each iteration. Create it once before the loop, and reuse it. Commented Mar 11, 2017 at 17:50

3 Answers 3

2

Moving this line of code: Output display = new Output(); outside the loop should give you the desired output.

Each time you create a new object, the number of that object is initialized to 0, which explains your current output. Reusing the object reuses number, and hence you get the desired output.

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

Comments

1

Every time you create a new Output(), you create a new object that starts from scratch. In this case, you are creating 5 new objects, incrementing each only once, and getting your series of 1s.

You will probably want to create a single Output outside of the loop and then simply increment inside the loop. That way it's the same object, and the values are thus maintained.

Comments

0

Your Output object is getting created for each loop and the number variable of the Output class is always instantiated to the default int value of 0. Hence each time it increments 0 to 1 and displays only 1.

You could either drop incrementing the number variable in the Output class and do the increment in the actual class and pass the value to the Output class.

public class Output {
    int number;
    public Output (int number) {
        this.number = number;
    }
    public void outputNumber() {
        System.out.println(number);
    }
}

And accordingly, change your calls to the Output class from the for loop in the Input class as well.

You also might want to change the for loop counter variable instantion from 0 to 1 and change the condition check to <=5 instead of <5.

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.