我有一个简单的程序,它使用方法来查找变量A
,B
,C
和D
中最大的变量和变量。只是为了探索,有没有办法将代码写入方法中以返回“A”,“B”等,而不仅仅是值?
public class methods
{
public static void main (String[] args)
{
int A=1, B=10, C=-5, D=20;
System.out.println("The largest of A and B is " + Largest(A,B));
System.out.println("The largest of A, B and C is " + Largest(A,B,C));
System.out.println("The largest of A, B, C and D is " + Largest(A,B,C,D));
System.out.println("The product of A and B is " + Product(A,B));
System.out.println("The product of A, B and C is " + Product(A,B,C));
System.out.println("The product of A, B, C and D is " + Product(A,B,C,D));
}
public static double Largest(int A, int B)
{
if (A > B)
return A;
else
return B;
}
public static double Largest(int A, int B, int C)
{
if (A > B && A > C)
return A;
else if (B > A && B > C)
return B;
else
return C;
}
public static double Largest(int A, int B, int C, int D)
{
if (A > B && A>C && A>D)
return A;
else if (B > A && B>C && B>D)
return B;
else if (C > B && C>A && C>D)
return C;
else
return D;
}
public static double Product(int A, int B)
{
return A*B;
}
public static double Product(int A, int B, int C)
{
return A*B*C;
}
public static double Product (int A, int B, int C, int D)
{
return A*B*C*D;
}
}
答案 0 :(得分:0)
为方法使用char返回类型而不是double。您还有一些应该修复的格式问题。你的方法标识符Largest()应该是最大的(),小写" l"。大写字母保留给类名和构造函数。您的变量A,B,C,D也应该是小写的。全部大写的变量只能用于最终变量。例如,
final int MAX = 100;
答案 1 :(得分:0)
最好使用这个逻辑来找出三个中最大的
public static double Largest(int A, int B, int C) // complexity of program is getting reduced just by minimizing the comparison.
{
if (A > B){ //a is greater than B
if(A>C)
return A; //return a if A is largest among three
else
return B // return B if B is largest among three
}else{
if(B>C) //this statement will execute if B>A.
return B; //return B if B is largest amoung three.
else
return C; // return C if C is largest among three.
}
}