Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 257
Jame Avatar asked Feb 19 '12 18:02

Jame


1 Answers

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).

like image 84
Oliver Charlesworth Avatar answered Nov 04 '22 21:11

Oliver Charlesworth