Jame
Jame

Reputation: 89

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

Upvotes: 8

Views: 275467

Answers (9)

rajiv baghel
rajiv baghel

Reputation: 29

  public class Practise {
    String a;

    public String getA() {
        return a;
    }
    public void setA(String a) {
        this.a = a;
    }
    void meth1(){

        this.setA("asd");

    System.out.println(a);


    }
    void meth2(){

        String b="qwerty";
        System.out.println(getA()+" "+b);

    }


    public static void main(String[] args) {

        Practise p= new Practise();
        p.meth1();
        p.meth2();
    }

}

Upvotes: -2

Shuvendu Roy
Shuvendu Roy

Reputation: 101

you can declare a 2-d array pointer as a member of the class. Then declare the size and value inside a member function. In this case you can access it form another function..

See the use of T[][] in this code

    public class Knapsack {

    //private static Scanner in;
    int T[][];

    int MaximumVal(int wt[],int val[], int total){
        int l=total;
        int m=val.length;
        T = new int[m+1][l+1];

        for (int i=0; i<=m; i++){
            for(int j=0; j<=l; j++){
                if(i==0 || j==0){
                    T[i][j]=0;
                    continue;
                }
                if(j-wt[i-1] >= 0){
                    T[i][j]=Math.max(T[i-1][j], val[i-1]+T[i-1][j-wt[i-1]]);
                }
                else{
                    T[i][j]=T[i-1][j];
                }
            }
        }
        return T[m][l];
    }

    void PrintPath(int wt[], int val[]){
        int i=T.length-1;
        int j=T[0].length-1;
        while(j!=0){
            if(i>0){
                while(T[i][j]==T[i-1][j]){
                    i--;
                }
            }
            System.out.print(wt[i-1]+" ");
            j=j-wt[i-1];
            i--;
        }
    }


    //Main Function with test case ::

    public static void main(String args[]){
        int wt[]={1,3,4,5};
        int val[]={1,4,5,7};
        Knapsack K = new Knapsack();

        System.out.print("Enter the total value:  ");
        //in = new Scanner(System.in);
        //int total = in.nextInt();

        int result = K.MaximumVal(wt,val,7); // pass total
        System.out.println("Total value is "+ result);

        K.PrintPath(wt,val);
    } 
}

Upvotes: 1

Atikant Negi
Atikant Negi

Reputation: 1

public class Test3 {
  double[][] a=new double[3][5];
  public void Scores() { 

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

 }  
}

Upvotes: 0

user620244
user620244

Reputation:

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.

Upvotes: 7

DunClickMeBro
DunClickMeBro

Reputation: 191

If you want to be able to use the 2d-matrix a, you need to declare it outside of your methods.

public class Test3 {
    double[][] a= new double[3][5]; 

    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]);
          }   
       }   
    }
    .......

You'll see that I've moved the declaration of a (formerly inside Scores(), and which I have commented out) outside the function, and it is now a field of the class Test3. When you declare a variable inside a function, it is local to that function. It cannot be seen by other functions, etc. If you declare it as a class field, your functions can see it. Take a look at this, as it may help. Language/VariableScope.htm">http://www.java2s.com/Tutorial/Java/0020_Language/VariableScope.htm The term "scope" just refers to the lifetime of a variable and where it can be seen. Hope this helps!

Upvotes: 0

Micah Armantrout
Micah Armantrout

Reputation: 6981

Pass in a argument or make a class var

Upvotes: 0

Parth Soni
Parth Soni

Reputation: 11658

just make a[i][j] as class variable, declare it outside the Scores(), just below the class name

public class Test3 {
  double[][] a= new double[3][5];
  public void Scores() { 
   ....
  }
  .....
}

Upvotes: 1

Diego
Diego

Reputation: 18359

Just move the declaration of a to make it a private property of class Test3, like this:

public class Test3 {

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

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

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

Upvotes: 17

Related Questions