java - 如何调用带参数的私有(private)方法

标签 java methods private-methods

我很难让带有参数的私有(private)方法在我的 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"));
    }
}

如果您发现需要对此实验进行说明,请查看实验表的 Google 文档:https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM

最佳答案

变量abc 在这里可以用作局部变量。这将允许您从 greatestCommonFactor 的参数列表中删除它们:

private int greatestCommonFactor() {

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

因为它们只在方法范围内是必需的。

关于java - 如何调用带参数的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13575777/

相关文章:

c++ - 在 C++ 中将数组作为方法的 const 参数传递

Objective-C:我应该声明私有(private)方法吗?

java - 模拟已标记为可访问的私有(private)方法的返回值

java - 如何保存(使微调器记住)微调器下拉列表中所选项目的位置

java - 初学者 Java - 将字符串从 First Middle Last 更改为 Last, First Middle

java - 逐行打印数字的递归方法

java - 用最少的计算量寻找素数的算法

java - 从适配器 -> CustomView 中更改 Activity 的 EditText

java - libGDX:在屏幕上移动多边形

java - 如何编写一个对某些参数返回 True 的私有(private)方法?