Doğukan Özdemir
Doğukan Özdemir

Reputation: 119

How to specify an int from another class

This is going to be a embarrassing question but I'm new to Java. I have a class that implements ActionListener with this code in it:

public class Shop1 implements ActionListener{
    public void actionPerformed(ActionEvent event){
        int alis = 0;
        alis++;
        System.out.println(alis);
    }
}

Everytime I press the button it shows 1. I know that everytime I press the button it sets the integer to 0, and adds 1, but I tried to put the integer outside the class but this time it doesn't recognize the int.

Upvotes: 1

Views: 90

Answers (1)

Lukas Knuth
Lukas Knuth

Reputation: 25755

What you're seeing here (the variables is always 0) is caused by the variables scope.

In Java, variables have block-scope, meaning that they are valid only in the block (and any blocks in that block) that they where created in. A simple example:

public void scope1(){
    if (something){
        int myint = 1;
        // possibly some other code here...
    }
    System.out.println(myint); // This will not compile, myint is not known in this scope!
    int myint = 1; // Declare myint in this scope
    System.out.println(myint); // now it works.
}

As you can see here, the first myint is declared in the if-blocks scope, causing it to not be valid outside the if-block. The second definition of myint is valid for the entire method-block (after the line it was created in).

Back to your problem: The variable you're creating has a block-scope of the actionPerformed()-method. Therefore, when that method returns, the variable will no longer be valid and it's value will be gone. When you enter the method again, you create a new variable in that scope.

To handle it the way you want, move the variable "up" to a scope higher than the method. Id'd suggest doing so in Shop1:

public class Shop1 implements ActionListener{

    private int alis;

    public void actionPerformed(ActionEvent event){
        alis++; // the variable is defined in the classes scope, so the values is "kept"
        System.out.println(alis);
    }

}

If anything is unclear, please comment!

Upvotes: 3

Related Questions