Search code examples
javamethodstostringcircuit

JAVA Using to.String() methood to return a sting of a resistor network


I'm a bit of a newbie to java and I'm having trouble with an assignment asking me to implement toString() method. The question asks that "write a method toString() which returns as a String the complete resistor network in the circuit and the resistance across the circuit. For example, the execution of the following piece of code:

SeriesCircuit s1 = new SeriesCircuit ( new Circuit( 2 ), new Circuit ( 3 ) );
ParallelCircuit p1 = new ParallelCircuit ( s1, new Circuit( 4 ) );
SeriesCircuit s2 = new SeriesCircuit ( p1, new Circuit( 1 ) );
ParallelCircuit p2 = new ParallelCircuit ( s2, new Circuit( 8 ) );
System.out.println( p2 + " = " + p2.getResistance() );

leads to the following output: ( ( ( ( 2.0 + 3.0 ) || 4.0 ) + 1.0 ) || 8.0 ) = 2.29702. Plus (+) stands for series while || represents parallel"

So far, ive made 2 subclasses one for SeriesCircuit

public class SeriesCircuit extends Circuit
{
      public Circuit a;
      public Circuit b;

    public double getResistance()
    {
        return resistance();
    }



    public SeriesCircuit(Circuit a, Circuit b)
    {
          this.a = a;
          this.b = b;
    }

    public double resistance() 
    {
           double rs1 =  a.resistance() + b.resistance();
           return rs1;
    }
}

Another for Parallel

public class ParallelCircuit extends Circuit
{

       public Circuit a;
       public Circuit b;

    public double getResistance()
    {
        return resistance();
    }



    public ParallelCircuit(Circuit a, Circuit b)
    {
          this.a = a;
          this.b = b;

    }

    public double resistance() 
    {
           double R1 = a.resistance();
           double R2 = b.resistance();
           double rp1 = 1.0 / (1.0 / R1  +  1.0 / R2);
           return rp1;
    }

}

While in the Circuit class, i don't have much going on at this time:

public class Circuit 
{


    public double resistance() 
    {
        return resistance();
    }


    public static void main(String[] args) 
    {


    }

}

Basically, I'm completely lost as to how I'm supposed to get the code the professor provided to execute and to have it output in a way he wants by using toString() method. Thanks.


Solution

  • In the class you need to write the toString() method for, try:

    public String toString()
    {
        String result = //build your string with whatever needs to be output
        return result;
    }
    

    As for the rest of your homework... you'll need to make more of an effort and come back with more specific questions.