TiaraHorizont TiaraHorizont - 5 months ago 7
Java Question

How do I connect two objects with a method to return a new object

I have 2 class objects A and B. Both contain an attribute called 'prob' (for probabillity).
Now I want to write a Method, which connects both objects and creates a new one, with a defined attribute 'prob' with "

A.prob(i)*B.prob(j)=C.prob(i+j).


Here is my code:

PMF add(PMF pmf){
for(int i=0; i<x; i++){
for(int j=0; j<x; j++){
C.prob[i+j]=prob[i]*pmf.prob(j);
}
}
}


This is in my PMF class. I have defined in my other class (the one with the main method, it is called "Hund" ) some objects:

public class Hund {

public static void main(String[] args){
PMF A= new PMF(6);
PMF B= new PMF(6);
PMF C= new PMF(6);
A.setProb(1, 1);
A.setProb(2, 1);
A.setProb(3, 1);
A.setProb(4, 1);
A.setProb(5, 1);
A.setProb(6, 1);
System.out.println(A.prob(6));

}
}


But now, it shows me an error "C cannot be resolved to a variable". How do I make it return a PMF-Type variable? Variations I tried are e.g.:

PMF add(PMF pmf){
PMF C= new PMF(x*2);
for(int i=0; i<x; i++){
for(int j=0; j<x; j++){
C.prob[i+j]=prob[i]*pmf.prob(j);
return C;
}
}
}
}


But then it shows me the error
This method must return a result of type of PMF.


What am I doing wrong? The Method name(type) is given, so I cannot change it into void add(PMF pmf) or smth.

Answer
PMF add(PMF pmf){
    PMF C= new PMF(x*2);
    for(int i=0; i<x; i++){
        for(int j=0; j<x; j++){
        C.prob[i+j]=prob[i]*pmf.prob(j);
        return C;
        }
    }
return C;
}