简体   繁体   中英

How can I pass a variable from one class to another?

So essentially what I want to do is to be able to:

class MainFile {
public static void main(String args[]){
class2 TEObject = new class2();
int var1 = 1;
int var2 = 1;
int var3 = 1;
int sc = 1;
TEObject.method1(sc, var1, var2, var3);
double[][] somearray = class2.out(somearray);
System.out.println(somearray);
}
}

and here is the second class:

    public class class2 {
private double Mult;
public double method1(int sc, int var1, int var2, int var3)
{
    double[][] somearray = 
            {{1,1,1,1,1,1,1,1,1,1,1,1},
            {1,0.5,1,0.5,0.5,1,1,2,2,0.5,1,2},
            {1,2,0.5,1,1,0.5,1,1,0.5,1,1,2},
            {1,2,1,0.5,0.5,1,1,0.5,2,1,0.5,2},
            {1,2,2,2,0.5,1,0.5,1,1,0.5,1,0.5},
            {1,1,0.5,1,1,0.5,2,0.5,1,2,2,0.5},
            {1,0.5,1,0.5,1,1,0.5,2,0.5,2,2,1},
            {1,0.5,2,2,2,2,0.5,0.5,0.5,1,1,0.5},
            {1,1,1,0.5,2,2,1,2,0.5,0.5,0.5,1},
            {1,1,0.5,1,2,0.5,2,0.5,1,0.5,2,1},
            {1,1,2,1,0.5,0.5,0.5,1,2,2,0.5,1},
            {1,0.5,0.5,2,1,2,2,1,1,1,0.5,0.5},
            };
    Mult = somearray[sc][var1]*somearray[sc][var2]*somearray[sc][var3];
    return Mult;//This needs to be returned for other methods in class2
}
public static double[][] out(double[][] somearray){
    return somearray;
}
//Some more methods go here

The problem I have here is that it asks me to put in a value when I try and call the method it says that the type is not applicable for the arguments. I can't put null there or else it will just print null.

Failing this I essentially want a way to be able to output from a class to my main class so that I can manipulate the array within the main class.

EDIT: I've updated the classes so they're more clear as to what I'm trying to do.

You have to store the return value of method2 in a variable in your Main class, like so:

double[][] somearray = class2.object.method2();

If you want to get somearray out of method1 this is not going to work as you can only return a single object in Java methods. The only way out would be a wrapper object that contains both somedouble and somearray . Or alternatively, if you don't need to return somedouble , choose somearray instead.

You are calling method2 with no arguments, yet it's expecting an argument somearray method 2 also has a return value, which you are not using. Take a step back, the intent in your calling code and the interface of class2, don't fit together at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM