[英]How do I call a private method with arguments
我很難獲得一個帶有參數的私有方法,可以在我的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
變量a
, b
和c
可以在這里用作局部變量。 這將允許您從參數列表中刪除greatestCommonFactor
:
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0;
...
因為它們僅在方法范圍內是必需的。
嗯,是的 你沒有把任何東西傳遞給greatestCommonFactor
。 當你沒有向方法傳遞足夠的參數時,我不確定你在toString()
方法中會發生什么。
你需要傳遞它們
output = output + this.greatestCommonFactor(1,2,3) + " \n";
問題是,除非你將參數傳遞給toString,否則這個代碼似乎非常有限。 或者,您需要在類上設置一些字段,並將其傳遞給您的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.