我的任务是创建一对重载方法,这些方法接受一些值并将它们相乘。我决定使用数组来保持整洁,但我的方法似乎没有按预期运行。如何将数组值传递给重载方法?
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 ;
}
}
答案 0 :(得分:0)
你能做的就是这个,
static int multiply(int... values) {
int product = 1;
for(int v : values) {
product *= v;
}
return product;
}
并称之为
int a = 1;
int b = 2;
int c = 3;
System.out.println(multiply(a));
System.out.println(multiply(a, b));
System.out.println(multiply(a, b, c));