如何在Java中调用具有数组类型的构造函数
我想在Motor类中创建一个constructor(Motor),我想在constructor1类中调用它,但我在这样做时出错了……我不知道为什么。 我从这周开始学习java 代码如下:如何在Java中调用具有数组类型的构造函数,java,arrays,Java,Arrays,我想在Motor类中创建一个constructor(Motor),我想在constructor1类中调用它,但我在这样做时出错了……我不知道为什么。 我从这周开始学习java 代码如下: class Motor{ Motor(int type[]){ int input; input=0; type = new int[4]; for(int contor=0; contor<
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();
}
}
}
级电机{
电机(int类型[]){
int输入;
输入=0;
类型=新整数[4];
对于(int contor=0;contor来说,不清楚您为什么首先在构造函数中放置参数-您没有使用它:
在最后一行中,您基本上覆盖了传入的任何值。为什么要这样做
如果确实要保留它,则需要创建一个数组以从调用方传入,例如
int[] types = new int[4];
// Populate the array here...
motor_type = new Motor(types);
目前的代码看起来有点混乱-您是真的希望电机的单个实例具有多个值,还是真的对电机的多个实例感兴趣
作为旁注,此语法:
int type[]
不鼓励使用。您应将类型信息保存在一个位置:
int[] type
此外,奇怪的是,您在Motor
中没有字段,而且您也从不使用在调用代码中创建的值。您可以尝试以下操作:
int intType[]={1,2,3}; //create some int array
Motor motor_type=new Motor(intType); //pass int array here
必须将[]作为参数传递给Motor
构造函数
像
由于您已经在Motor
类中定义了参数化构造函数,所以默认情况下不会创建任何参数构造函数,这就是为什么在下面的行中出现错误的原因
motor_type = new Motor(); // Error here , because no-arg constructor not defined.
构造函数有一个int[]
类型的参数,但您不能将任何内容作为参数传递。您需要创建一个数组,并将其作为参数传递:
int[] type = new int[4];
Motor m = new Motor(type);
请注意,此构造函数参数一点用处都没有,因为您在构造函数中不使用它。相反,您使用新数组覆盖它。我只需删除数组参数。请发布错误,否则我们无法真正帮助您。。
motor_type = new Motor(); // Error here , because no-arg constructor not defined.
int[] type = new int[4];
Motor m = new Motor(type);