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
4

4 に答える 4

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}); 
    
于 2012-11-15T18:42:24.383 に答える
1

This should do it: new Temperature(new int[] {1,2,3,4,5,6,7})

于 2012-11-15T18:44:29.537 に答える
1

You can do it by the following way

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);
    }




}
于 2012-11-15T18:44:44.267 に答える
0
 public static void main(String[] args)
    {
    Temperature i = new Temperature(new int[] {1,2,3,4,5,6,7});
    }
于 2012-11-15T18:42:50.260 に答える