创建一个接受整数数组的构造函数

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
5个回答

7
  • For the current invocation, you need a var-args constructor instead. So, you can either change your constructor declaration to take a var-arg argument: -

    public Temperature(int... a) {
         /**** Rest of the code remains the same ****/
    }
    
  • or, if you want to use an array as argument, then you need to pass an array to your constructor like this -

    Temperature i = new Temperature(new int[] {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);
    }




}

1

这应该可以解决问题: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});
    }

0
Temperature i = new Temperature(1,2,3,4,5,6,7);

当您尝试初始化此构造函数时,请考虑它具有int值,如果出现以下错误消息:

required: int[] found: int,int,int,int,int,int,int reason: actual and formal argument lists differ in length 在初始化值之前,请将其声明为单独的变量。

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

public class HashPrint implements Serializable
{
    private int[] temps = new int [7];
    public HashPrint(int[] a)
    {
        this.temps=a;

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

        HashPrint i = new HashPrint(arr);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接