Search code examples
javamethodsprivate-methods

How do I call a private method with arguments


I'm having an extremely difficult time getting a private method with arguments to be usable in my toString method but have no idea how to get the two methods to cooperate.

main class:

import static java.lang.System.*;

public class Triples
{
 private int number;

public Triples()
{
    //this(0);
}

public Triples(int num)
{
    number = num;
}

public void setNum(int num)
{
    number = num;
}

private int greatestCommonFactor(int a, int b, int c)
{
    int max = number;

    for(int n = 1; n <= max; n++)
    {

    for(a = n; a <= max; a++)
    {
        a = n;
        for(b = a +1; b <= max; b++)
        {
            b =n;
            for(c = b + 1; c <= max; c++)
            {
                c = n;
                if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
                {
                    if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
                    {
                        if(a%2<=1 && b%2<=1 && c%2<=1)
                        {

                            String last = a + "" + b + c;
                        }
                    }
                }

            }

        }

    }
    }

    return 1;
}

public String toString()
{
    String output="";
    output = output + this.greatestCommonFactor( ) + " \n";


    return output;
}
}

and for cross-referencing my runner class:

import static java.lang.System.*;

import java.util.Scanner;

public class Lab11j
{
 public static void main(String args[])
  {
       Scanner keyboard = new Scanner(System.in);
        String choice="";
            do{
                out.print("Enter the max number to use : ");
                int big = keyboard.nextInt();


                    //instantiate a TriangleThree object
             Triples triple = new Triples(big);
                //call the toString method to print the triangle
                out.println( triple );

                System.out.print("Do you want to enter more data? ");
                choice=keyboard.next();
            }while(choice.equals("Y")||choice.equals("y"));
    }
}

if you find you need clarification of this lab, here's a Google docs of the labsheet: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM


Solution

  • The variables a, b & c can be used as local variables here. This would allow you to remove them from the argument list of greatestCommonFactor:

    private int greatestCommonFactor() {
    
       int a = 0;
       int b = 0;
       int c = 0; 
       ...
    

    as they are only required within the scope of the method.