Java:在方法中返回char而不是double
我有一个简单的程序,它使用方法查找变量Java:在方法中返回char而不是double,java,methods,char,return,double,Java,Methods,Char,Return,Double,我有一个简单的程序,它使用方法查找变量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 " + Larges
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;
}
}
方法使用char返回类型而不是double。还有一些格式问题需要解决。您的方法标识符max()应该是max(),带有小写字母“l”。类名和构造函数保留大写字母。此外,变量A、B、C、D也应该是小写的。所有大写的变量只能用于最终变量。比如说,
final int MAX = 100;
最好用这个逻辑找出三者中最大的一个
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.
}
}
您的方法返回一个
double
,因为您将double
作为返回类型。如果要返回char
,请将返回类型更改为char
,并返回char
文本而不是数字输入(例如If(a>B)返回'a';
)哇。很简单,我跳过了。谢谢。当A=3
,B=1
,C=5
时,它返回1。