Reputation: 11
When I tried to build this program there's always a error like "non-static method referenced from a static context" I think that because I can use "addto" function in "main". So how can I solve this problem? I need a public arraylist because I have to do the calculations in "addto"
Thx!
public class Calculation {
ArrayList<int[]> cal = new ArrayList<>();
public static void main(String[] args) {
System.out.println(addto(3,5));
}
String addto(int figone, int figtwo){
........do the calculations by using arraylist cal
}
}
Upvotes: 0
Views: 400
Reputation: 718856
Really simple?
System.out.println(new Calculation().addto(3,5));
or
Calculation calculation = new Calculation();
System.out.println(calculation.addto(3,5));
// and use 'calculation' some more ...
(You could also add a static
modifier to the addto
method declaration, but you would then need to make cal
static too so the addto
can use it. Bad idea.)
OK. So what the compilation method is actually saying is that addto
is declared as an instance method ... but you are trying to call it without saying which instance to use. In fact, you are trying to call it as if it was a static method.
The "fix" (see above) is to create an instance and call the method on that.
Upvotes: 1
Reputation: 1117
You need to instantiate a Calculation object inside the main function in order to use Calculation's non-static methods.
Non-static methods only "exist" as members of an object (which you can think of as instances of classes). In order to make this work you'd need to write:
System.out.println(new Calculation().addto(3, 5))
Upvotes: 4