How would I return my x and y variable into main in order to perform the addition?
Thanks in advance for the help!
import java.util.Scanner;
public class calling {
public static int x;
public static int y;
public static void num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
}
public static void num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
}
public static void main(String[] args){ **//place to return variables.**
num1();
num2();
System.out.print("The sum of the two numbers is: " + (x+y));
}
}
You shouldn’t be using static data members or methods – those should only be used when the member of method applies to all instances of a class.
In this case the only static method should be
mainand that should only create a single instance of the current class.mainshould almost never do any real work – although in this trivial example I suppose an exception could be made.You should ideally also only create a single
Scannerobject – theScannerclass is perfectly capable of reading a continuous stream of numbers without you needing to create a new one over and over for each number to be read.In the code below I just create one and use it twice directly.
Alternatively the scanner object could have been stored as a member variable, as in this example: