如何在另一种方法中使用一种方法的变量? [英] How to use a variable of one method in another method?

查看:153
本文介绍了如何在另一种方法中使用一种方法的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在方法 Scores() a [i] [j] c>在以下代码中的方法 MD() sumD()中使用它:

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:

在我的代码中,方法 MD() sumD()无法得到结果。

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();

 }  
}

提前致谢。

推荐答案

你做不到。方法中定义的变量是该方法的局部变量。

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

这篇关于如何在另一种方法中使用一种方法的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆