As the title explains I am hoping to be able to set an Instance Variable using data produced by a calculation contained within a Method.
I produced an example code to demonstrate what I'm trying to do, as well as a solution I pieced together after scouring the internet. Obviously though, I failed to successfully replicate what others had done.
Thanks in advance for your help.
This code is intended to set the instance variable of "Max" to the value of "6" using the "myMethod" method, and then use the "printMethod" to print the value of "Max".
public class Main {
//Main class, Of Coruse.
private int Max;
//The value I wish to be changed by the method.
public int getMax() {
return Max;
}//The process which is supposed to get the value from the method.
public static void main(String[] args) {
Main Max = new Main();
{
Max.printMax();
}
}//The main method, and non-static reference for printMax.
public void myMethod() {//Method for assigning the value of "Max"
int Lee = 6;
this.Max = Lee;
}
public void printMax() {//Method for setting, and printing the value of "Max"
Main max = new Main();
int variable = max.getMax();
System.out.println(variable);
}
}
I think you have some misunderstandings of how instances of a class work. I recommend you to learn the basics of OOP first.
Anyway, although you didn't tell me what should be the expected result, I guess that you want to print 6
. So here's the solution:
private int Max;
public int getMax() {
return Max;
}
public static void main(String[] args) {
Main Max = new Main();
Max.printMax();
}
public void myMethod() {
int Lee = 6;
this.Max = Lee;
}
public void printMax() {
this.myMethod();
int variable = this.getMax();
System.out.println(variable);
}
Let me explain what I have changed.
main
method, there is no need for the {}
after new Main()
, so I deleted them.printMax
, there is no need to create a Main
instance again because this
already is one.6
was because the variable max
was never changed. Why? Because you just declared a method that changes max
, but that method (myMethod
) is not called! So I just added a line to call myMethod
.