如何在Java中调用具有数组类型的构造函数

时间:2012-10-12 13:07:11

标签: java arrays

我想在Motor类中创建一个构造函数(Motor),我想在Contructor1类中调用它,但是当我这样做时我有一个错误.....我不知道为什么。 我刚刚从本周开始学习java。

这是代码:

  class Motor{
        Motor(int type[]){
            int input;
            input=0;
            type = new int[4];
            for(int contor=0; contor<4; contor++){
                System.out.println("Ininsert the number of cylinders:");
                Scanner stdin = new Scanner(System.in);
                    input = stdin.nextInt();
                type[contor] = input;
                System.out.println("Motor with "+type[contor]+" cylinders.");
            }
        }
    }

    public class Contructor1 {
        public static void main(String[] args){
            Motor motor_type;
            for(int con=0; con<4; con++){
                motor_type = new Motor();
            }

            }

        }

4 个答案:

答案 0 :(得分:7)

目前尚不清楚为什么你首先在构造函数中放置一个参数 - 你不是使用它:

Motor(int type[]){
    int input;
    input=0;
    type = new int[4];

在最后一行中,你基本上会覆盖传入的任何值。你为什么这样做?

如果你希望保留它,你需要创建一个从调用者传入的数组,例如

int[] types = new int[4];
// Populate the array here...
motor_type = new Motor(types);

目前的代码看起来有点混乱 - 你是否真的打算让Motor的单个实例拥有多个值,或者你真的对多个实例感兴趣Motor

作为旁注,这句语法:

int type[]

是气馁的。您应该将类​​型信息保存在一个位置:

int[] type

此外,奇怪的是Motor中没有字段,并且您从不使用您在调用代码中创建的值。

答案 1 :(得分:2)

构造函数的参数类型为int[],但您不会传递任何参数作为参数。您需要创建一个数组,并将其作为参数传递:

int[] type = new int[4];
Motor m = new Motor(type);

请注意,此构造函数参数完全没用,因为您在构造函数中没有对它执行任何操作。而是用新数组覆盖它。我只是删除数组参数。

答案 2 :(得分:1)

您必须将[]作为参数传递给Motor构造函数。

喜欢

 new Motor (new int[] {0,1,2,3});

由于您在Motor类中定义了参数化构造函数,因此默认情况下不会创建no-arg构造函数,因为您在下面的行中会出现错误

 motor_type = new Motor();  // Error here , because no-arg constructor not defined. 

答案 3 :(得分:0)

您可以尝试以下操作:

int intType[]={1,2,3}; //create some int array
Motor motor_type=new Motor(intType); //pass int array here