Reputation: 23
I'm learning java and was trying to create a simple program to help me find a way (if there is one) to access non-static methods inside the main method of the same class. This is what I have so far
import java.util.Scanner;
public class MethodVariables
{
public int num1;
public int num2;
public int add = (num1 + num2);
public int sub = (num1 - num2);
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Please enter the first number: ");
String num1 = input.nextLine();
System.out.println("Please enter the second number: ");
String num2 = input.nextLine();
input.close();
// I know these wouldn't work this way but this is just to show what I am trying to accomplish
addition(add);
subtraction(sub);
}
public void addition(int add)
{
System.out.println("The sum of the two is: " +add);
}
public void subtraction(int sub)
{
System.out.println("The diference of the two is: "+sub);
}
}
If anyone knows what I am overlooking I'd appreciate the help.
Upvotes: 2
Views: 1739
Reputation: 1525
This is not related to the original question, but is worth pointing out:
public int add = (num1 + num2);
This will not work as you expect. If you want a function that adds two numbers, just make a function that adds two numbers.
public int add(int num1, int num2) {
return num1 + num2;
}
public int subtract(int num1, int num2) {
return num1 - num2;
}
Upvotes: 0
Reputation: 59607
Sure, just create an instance of the class in main
:
MethodVariables instance = new MethodVariables();
instance.addition(num1);
instance.subtraction(num2);
Since addition
and subtraction
are instance methods, then you'll always need an instance of the class to call them on.
Upvotes: 2