1

我很难获得一个带有参数的私有方法,以便在我的 toString 方法中使用,但不知道如何让这两种方法合作。

主类:

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

并交叉引用我的跑步者课程:

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

如果你发现你需要澄清这个实验室,这里是实验室表的谷歌文档: https ://docs.google.com/open?id= 0B_ifaCiEZgtcX08tbW1jNThZZmM

4

3 回答 3

3

变量a, b&c在这里可以用作局部变量。这将允许您从以下参数列表中删除它们greatestCommonFactor

private int greatestCommonFactor() {

   int a = 0;
   int b = 0;
   int c = 0; 
   ...

因为它们仅在方法范围内需要。

于 2012-11-27T01:00:03.420 回答
1

嗯,是的。你没有传递任何东西给greatestCommonFactor. toString()当您没有向方法传递足够的参数时,我不确定您期望在方法中发生什么。

于 2012-11-27T00:53:53.413 回答
0

你需要像这样传递它们

output = output + this.greatestCommonFactor(1,2,3) + " \n";

问题是,除非您将参数传递给 toString,否则,此代码似乎非常有限。或者,您需要在类上设置一些字段,其中包含将传递给您的函数的内容。

于 2012-11-27T00:57:41.870 回答