In the java programming language, how do you set a new value for a public integer, so that an outside method in an outside class can get this value, by simply calling the variable name. I have example code:
package build;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.init();
}
public int myVar = 1;
EDIT:
More specific question: How can I get the variable’s updated value, not it’s starting value without passing it on to a the method?
public void init() {
Retrieve ret = new Retrieve();
int i = 0;
for(int n = 1; n > 0; ++n) {
myVar = myVar + 1;
System.out.println("Value: " + myVar);
i = ret.init();
System.out.println("Retrieved Value: " + i);
}
}
int getValue() {
int b = myVar;
return b;
}
}
and for Return:
package build;
public class Retrieve {
public int init() {
Main main = new Main();
int a = 1;
a = main.getValue();
return a;
}
}
In the example above, how would I set the variable “myVar” to a value other than one, so that when I call the ‘init’ method in the ‘return’ class, it returns that new value, rather than 1, the starting value?
There’s something very wrong with your object relationship.
The main problem is in Retrieve.init()
Every time you call init() you are making a new instance of main, so main.myVar will be 1. I assume you wanted to call the value of the first main.
and in Main.init change
to