First of all I am new to JAVA, so I still dont understand everything and how it works. But I was working on something and was wondering if it could be done like this.
import java.util.Scanner;
public class Main {
public static int calc(){
Scanner sc = new Scanner(System.in);
String number1 = sc.nextLine();
int y = Integer.parseInt(number1);
System.out.println("+");
String number2 = sc.nextLine();
int z = Integer.parseInt(number2);
int Result = y + z;
sc.close();
return Result;
}
public static void printText(){
System.out.println(Result);
}
public static void main(String args[]) {
calc();
printText();
}
}
In the first method I was calculating the "Result" and in the second I just wanted it to make it so that it takes the "Result" and prints it.. but How I understand is that what happens in a method stays in the method. But I was wondering if it is possible to let method "printText" access the int from "calc".
I know I could place the code into the main and print it from there, but still it buggs me if it could be done like that :)
You can't access a local variable from a different method, no. (Once the method has completed, the local variable doesn't exist any more.) However, you can use the return value from your calc
method, and pass that to the printText
method:
public static void printText(int result) {
System.out.println(result);
}
public static void main(String args[]) {
int result = calc();
printText(result);
}
See more on this question at Stackoverflow