0

How do I update an integer in the main method according to the number of times I call a method from another class?

I have a jButton in the jFrame that runs a method(if conditions are met) from another class every time the button is clicked. I want it in a way that the integer is updated every time the button is click AND the particular method from the other class is called.

Thank for the help!

EssVee
  • 93
  • 7
  • Make the integer variable `public`, and set it from the method called... – Usagi Miyamoto Aug 04 '17 at 12:59
  • 1
    As I understant your question, I think you need to declare your integer as `public static` and increment it in your method. Take a look at https://stackoverflow.com/questions/8250153/set-and-get-a-static-variable-from-two-different-classes-in-java – Grechka Vassili Aug 04 '17 at 13:00
  • First of all : what is blocking you ? In what way do you think your question is a useful question for the community ? Did you check that there wasn't already an answered question solving your case ? Then : use an AtomicInteger and pass it to the method in question or register a listener. – Jeremy Grand Aug 04 '17 at 13:01
  • It seems like you struggle with some basics of **OOP**. You need to make sure that, at the location where you want to edit the variable, it is known. Therefore you have many options, they depend on the structure you want to build. You could just make the variable **public**, you could offer **getter-methods**, you could pass a **reference** to the variable to the consumer and so on. Can you show us your code? Then we can try to identify the correct action and help you better. – Zabuzard Aug 04 '17 at 13:02

1 Answers1

1

If you are trying to update a local variable declared within the main method from outside of the method, then I'm afraid you can't.

public static void main(String[] args) {
    int counter = 1;
    doSomething();  // there is no way that 'doSomething()' can update 'counter'
}

Java has neither first-class closures or the ability to pass the address of a variable as a parameter (i.e. call by reference). These are the two approaches that other languages typically use to implement out-of-scope mutation of local variables.


But the fact that you are trying to do this suggests that you are missing something important about OO programming and design. You should rewrite your code to do one or more of:

  • return the value or values as a result or an object that holds the results
  • pass an object as a parameter and set the values in the object
  • use a static variable
  • use a shared object that is set up using dependency injection

(Static variables are a poor choice ... for various reasons ... and DI is too complicated for a beginner, and entails a lot of dependencies.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216