[java] How to use a variable of one method in another method?

I want to know how can I use the variable a[i][j] in the method Scores() to use it in the methods MD() and sumD() in the following code:

In my code, the methods MD() and sumD() can't get the result.

public class Test3 {

  public void Scores() { 
   double[][] a= new double[3][5];
   int i,j;

   for(i=0; i<3; i++ ){
        for(j=0; j<5; j++){
                a[i][j]= (double) Math.random(); 
                System.out.println("a[" + i + "][" + j + "] = " +a[i][j]);
        }   
   }   
}
  public void MD(){
   double[][] b =new double[3][5];
   int [] m = new int[5];
   int i,j;
   //double[][] a= new double[3][5];

   for(j= 0; j<5; j++)
        for(i=0 ; i<3 ; i++) 
        {
           b[i][j]=0.0;                                                    
           if(a[i][j]>0.0) 
              m[j]++;
        }   
    for(j= 0; j<5; j++){
        for(i=0 ; i<3 ; i++) {
           if(a[i][j] > 0.0){
               b[i][j]=a[i][j]*m[j];
               System.out.println("b[" + i + "][" + j + "] = " + b[i][j]);
           }    
       }        
   }                
}

public void sumD(){

int i,j,n;
double[] sum= new double[3];
double[] k= new double[3];
//double[][] a= new double[3][5];

  for(i=0; i<3; i++){
      n=0;
      sum[i]=0.0;
      for(j=0; j<5; j++){
          if(a[i][j]>0.0){
              sum[i] += (a[i][j])*2;
              n++;
          }                
      }
      k[i]=sum[i]/n;
      System.out.println("k[" + i + "] = " + k[i]); 
 }
}

public static void main(String[] args){
    Test3 print= new Test3();
    print.Scores();
    print.MD();
    print.sumD();

 }  
}

Thanks in advance.

This question is related to java methods multidimensional-array

The answer is


You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array