我正在尝试提示用户输入 3 个数字。输入这些数字后,我将添加最大的两个数字。主要方法是处理所有打印语句并调用其他方法。我不允许使用 for 循环来解决这个问题。 main 中的变量应该传递给其他方法。
我不知道为什么我无法从 main 调用该方法。这是我的代码:
public class HW {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers.");
int x = console.nextInt();
int y = console.nextInt();
int z = console.nextInt();
HW.calLargestSum(); //ERROR
HW.calLargestSum(int x, int y, int z); //STILL ERROR
}
public int calLargestSum(int x, int y, int z){
if ( x > y && x > z && y > z )
return x + y;
else if ( y > x && y > z && x > z )
return y + x;
else if ( z > x && z > y && y > x )
return z + y;
return 0;
}
}
最佳答案
您无法调用它,因为您尚未实例化硬件对象。两种解决方案:
HW hw = new HW();
hw.calLargestSum();
或者使方法静态,这样就不需要实例化它:
public static int calLargetSum();
进一步...好吧,这么多问题...
HW.calLargestSum(); //ERROR
没有方法calLargestSum()
,只有calLargestSum(int x, int y, int z)
。
HW.calLargestSum(int x, int y, int z); //STILL ERROR
您需要在此处传递值。 int x
不是一个值。您需要传递如下值:
HW.calLargestSum(1, 2, 3);
关于java - 提示用户输入3个数字,添加最大的2个数字(无法调用方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26556174/