2012-11-15 57 views
3

如何將一個整型數組傳遞給我的構造函數?製作一個接受整型數組的構造函數

這裏是我的代碼:

import java.io.*; 
import java.util.*; 

public class Temperature implements Serializable 
{ 
    private int[] temps = new int [7]; 
    public Temperature(int[] a) 
    { 
     for(int i=0; i < 7; i++) 
     { 
      temps[i] = a[i]; 
     } 

    } 
    public static void main(String[] args) 
    { 
     Temperature i = new Temperature(1,2,3,4,5,6,7); 
    } 
} 

給出的錯誤是:

Temperature.java:17: error: constructor Temperature in class Temperature cannot be applied to given types; 
     Temperature i = new Temperature(1,2,3,4,5,6,7); 
         ^
    required: int[] 
    found: int,int,int,int,int,int,int 
    reason: actual and formal argument lists differ in length 
1 error 

回答

7
  • 對於當前調用,你需要一個var-args constructor 代替。所以,你可以改變你的constructor聲明採取 var-arg參數: -

    public Temperature(int... a) { 
        /**** Rest of the code remains the same ****/ 
    } 
    
  • ,或者,如果你想使用an array作爲參數,那麼你需要pass an array到你的構造這樣的 -

    Temperature i = new Temperature(new int[] {1,2,3,4,5,6,7}); 
    
0
public static void main(String[] args) 
    { 
    Temperature i = new Temperature(new int[] {1,2,3,4,5,6,7}); 
    } 
1

這應做到: 新的溫度(新我NT [] {} 1,2,3,4,5,6,7)

1

您可以通過以下方式

import java.io.*; 
import java.util.*; 

public class Temperature implements Serializable 
{ 
    private int[] temps = new int [7]; 
    public Temperature(int[] a) 
    { 
     for(int i=0; i < 7; i++) 
     { 
      temps[i] = a[i]; 
     } 

    } 
    public static void main(String[] args) 
    { 
     int [] vals = new int[]{1,2,3,4,5,6,7}; 
     Temperature i = new Temperature(vals); 
    } 




} 
相關問題