I'm new to programming, I need a little help understanding how to use the same variable in many methods. Thanks in advance!
I have a class with some static variable declared before the methods, after I have a first method which calculate some value and a second method which print the results. In the printing method I want to print the initial input but it's always 0. Can someone help me to understand how to update the global variable please?
I tried to return the value from the method but it doesn't update the "global" variable
import java.util.Scanner;
public class Main {
public static boolean evenNumber = false;
public static boolean positiveNumber = false;
public static boolean positiveEvenNumber = false;
public static int intInputNumber;
public static void main(String[] args) {
testEvenPositive();
printMethod();
}
public static int testEvenPositive(){
System.out.println("Please insert a number, it will be evaluated to even or not and id it's positive or not.");
Scanner scanner = new Scanner(System.in);
int intInputNumber = Integer.parseInt(scanner.nextLine());
if (intInputNumber > 0) {
positiveNumber = true;}
if (intInputNumber % 2 == 0) {
evenNumber = true;}
if (intInputNumber % 2 == 0 && intInputNumber > 0) {
positiveEvenNumber = true;}
return intInputNumber;
}
public static void printMethod() {
System.out.println(Main.intInputNumber + " is an even number: " + evenNumber);
System.out.println(Main.intInputNumber + " is a positive number: " + positiveNumber);
System.out.println(Main.intInputNumber + " is a positive even number: " + positiveEvenNumber);
}
}
testEvenPositiveyou're never changing the value of the field - you're using a newly-declared local variable. If you changeint intInputNumber = ...to justintInputNumber = ...in the method that will fix the problem. I generally wouldn't use static fields like this, but I understand this is just while you're learning.