0
我的任務是創建一對重載的方法,它接受一些值並將它們相乘。我決定使用一個數組保持整潔,但我的方法似乎沒有像預期的那樣運行。我如何傳遞一個數組值到一個重載的方法?如何將數組值傳遞給重載方法?
import java.util.Scanner ;
class Lab8Ex4 {
public static void main (String[] args) {
//Declare Variables
int[] numbers = new int[5] ;
//Setup a scanner.
Scanner scan = new Scanner (System.in) ;
///////////////////
//Get User Input//
///////////////////
for (int j = 0 ; j < 5 ; j++) {
System.out.println ("Please enter a number: ") ;
numbers[j] = scan.nextInt() ;
}
//Call the first method
multiply (numbers[0], numbers[1]);
//Call the second method
multiply (numbers[2], numbers[3], numbers[4]);
}
//Overloaded Method - Multiplication of two numbers.
static int multiply (int a, int b) {
int sum = a * b ;
return sum ;
}
//Overloaded Method - Multiplication of three numbers.
static int multiply (int a, int b, int c) {
int sum = a * b * c ;
return sum ;
}
}
什麼不能達到預期效果?你期望會發生什麼?這兩種方法都會被調用並計算結果,但是您不會使用結果。 –
(另外,變量'sum'應該被稱爲'product') –
正如@ModusTollens所說,你的方法被調用,但你對它們什麼都不做。嘗試記錄結果,例如'System.out.println(「First multiply result is:」+ multiply(numbers [0],numbers [1]));' –