Question about Java (from newbie).

There is a main method, which through the scanner receives 3 variables from the user, fills in some arrays, and does some calculations.

In this method you need to count f (x);

I decided to make another method for counting f (x) - to which we will send X and receive a return - answer after calculations and depending on the answer - further use the main method anyway.

The problem is that in the new method, you need to have access to all the variables and arrays of the main method (actually for the same calculations).

How to make all variables and arrays of the method main accessible to other methods in the class?

Thanks for the answer.

  • one
    Either declare them outside the main method, and above and make them static, or pass them in the parameters to the required method - Mikhail Ketov

3 answers 3

The simplest thing is to remove variables from the method:

public class sovet { static int[] ints = new int[10]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); for (int i = 0; i < ints.length; i++) { ints[i] = scan.nextInt(); } } } 
  • Thank. Removed them from the main method. - mDobroch

3 solutions.

  1. as described static fields in the class where will be recorded.
  2. create an instance of the class and create non-static fields in it.
  3. pass to method as parameter.

The worst solution IMHO is static fields (option 1). For your method for calculating the value of a function is tightly attached to these fields. But it is also the fastest.

IMHO methods that calculate the function values ​​for good should receive the input data as parameters and take constants from the fields.

    Create static variables in the class and use them in the main method and in other methods of this class.

    • Thank. Removed them from the main method. - mDobroch