我想在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚为什么你首先在构造函数中放置一个参数 - 你没有使用它:
Motor(int type[]){
int input;
input=0;
type = new int[4];
Run Code Online (Sandbox Code Playgroud)
在最后一行中,你基本上都会覆盖传入的任何值.你为什么这样做?
如果你也想保留它,你需要创建一个数组从来电者,如通过
int[] types = new int[4];
// Populate the array here...
motor_type = new Motor(types);
Run Code Online (Sandbox Code Playgroud)
目前的代码看起来有点混乱 - 你真的打算让一个实例Motor有多个值,或者你真的对多个实例感兴趣Motor吗?
作为旁注,这个语法:
int type[]
Run Code Online (Sandbox Code Playgroud)
气馁.您应该将类型信息保存在一个位置:
int[] type
Run Code Online (Sandbox Code Playgroud)
此外,奇怪的是你没有字段Motor,并且你从不使用你在调用代码中创建的值.
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |