2017-02-17 29 views
1

我正在練習變量參數,我希望能夠找到數字的乘積。這是我能弄清楚如何去做的第一種方法。我覺得我可以在不使用ArrayList的情況下做到這一點,但我看不出如何。使用變量參數來查找沒有ArrayList的數字乘積?

import java.util.*; 

public class variableMethod 
{ 
    public static void main(String[] satharel) 
    { 
     System.out.printf("The product of 5 and 10: \t\t%3d%n", productFinder(5, 10)); 
     System.out.printf("The product of 2 and 3 and 4: \t\t%3d%n", productFinder(2, 3, 4)); 
     System.out.printf("The product of 1 and 2 and 3: \t\t%3d%n", productFinder(1, 2, 3)); 
     System.out.printf("The product of 7 and 2 and 4 and 5: \t%3d%n", productFinder(7, 2, 4, 5)); 

    } 

    public static int productFinder(int... num) 
    { 
     ArrayList<Integer> numbers = new ArrayList<Integer>(); 

     for(int n : num) 
      numbers.add(n); 

     int first = numbers.get(0); 

     for(int i = 1; i < numbers.size(); i++) 
      first *= numbers.get(i); 

     return first; 
    } 
} 

回答

1

是的,你可以,可變參數被視爲數組看到這個answer這樣你就可以遍歷他們像一個正常的數組:

public static int productFinder(int... num) 
{ 
    int product = 1; 
    for(int i = 0; i < num.length; i++) { 
     product *= num[i]; 
    } 
    return product; 
} 
+0

啊,這非常有幫助!除了我會寫「product * = num [i]」而不是「product * = num [1]」 – atlantoc

+0

我已編輯:) – Fahad

3

當然,你不需要在那裏列表。只需遍歷數組並製作產品即可。

public static int productFinder(int... num) { 
     int result = 1; 
     for (int i = 0; i < num.length; i++) { 
      result *= num[i]; 
     } 
     return result; 
    } 
+0

我可能會與結果== 1 – Dirk

+1

@Dirk三江源啓動救生員:D –

+0

哇。爲什麼我不能看到這樣一個簡單的答案?非常感謝!我喜歡這種簡單。 – atlantoc

相關問題