Sử dụng varargs với phương thức trong Java



Miêu tả vấn đề

Cách tạo một phương thức lấy tham số độ dài biến như là một input trong Java?

Giải pháp

Ví dụ sau minh họa cách tạo phương thức sumvarargs() mà lấy biến int như là một tham số và trả về tổng các tham số như là một input trong Java.

public class Main {
   static int  sumvarargs(int... intArrays){
      int sum, i;
      sum=0;
      for(i=0; i< intArrays.length; i++) {
         sum += intArrays[i];
      }
      return(sum);
   }
   public static void main(String args[]){
      int sum=0;
      sum = sumvarargs(new int[]{10,12,33});
      System.out.println("The sum of the numbers is: " + sum);
   }
}

Kết quả

Code trên sẽ cho kết quả sau:

The sum of the numbers is: 55

phuong-thuc_trong_java.jsp