Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a constructor that accepts an integer array

How can I pass in an integer array into my constructor?

Here is my code:

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

The error given is:

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
like image 474
bob t Avatar asked Sep 01 '26 00:09

bob t


1 Answers

  • 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}); 
    
like image 169
Rohit Jain Avatar answered Sep 03 '26 13:09

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!