2
我是Java編程的完全新手,我想在運行時動態創建Java對象,我已經檢查了表單並嘗試了一些代碼,但似乎沒有任何工作。在循環中動態創建對象
這裏是我的代碼..所有的幫助是非常讚賞:)
import java.util.Scanner;
public class Main{
public static void main(String[] args){
String carName;
String carType;
String engineType;
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
for(int i = 0; i <limit; i++){
Cars cars[i] = new Cars();
System.out.print("Enter the number of Car Name - ");
carName = in.nextLine();
System.out.print("Enter the number of Car Type - ");
carType = in.nextLine();
System.out.print("Enter the Engine Type - ");
engineType = in.nextLine();
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
String a = cars[i].getCarName();
String b = cars[i].getCarType();
String c = cars[i].getEngineeSize();
System.out.println(a,b,c);
}
}
}
汽車類看起來是這樣的..
public class Cars{
public String carName;
public String carType;
public String engineeSize;
public void Cars(){
System.out.println("The Cars constructor was created ! :-) ");
}
public void setCarName(String cn){
this.carName = cn;
}
public void setCarType(String ct){
this.carType = ct;
}
public void setEngineeSize(String es){
this.engineeSize = es;
}
public String getCarName(){
return this.carName;
}
public String getCarType(){
return this.carType;
}
public String getEngineeSize(){
return this.engineeSize;
}
}