Динамически создавать объекты в цикле
Я - новичок в программировании на 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;
}
}
1 ответ
Вы на правильном пути, хотя есть несколько ошибок и ненужных битов.
Класс автомобилей
Ваш класс автомобилей был в основном хорошо, (хотя на мой взгляд Car
было бы больше смысла) однако ваш конструктор не имеет смысла, у вас было public void Cars()
, void
означает "этот метод ничего не возвращает", но вы хотите вернуть Cars
объект, то есть ваш конструктор должен стать:
public Cars()
{
System.out.println("The Cars constructor was created ! :-) ");
}
Ваш основной класс
Вы были очень близки здесь, ваша основная проблема заключалась в создании cars
массив limit
раз:
for(int i = 0; i < limit; i++)
{
Cars cars[i] = new Cars();
//Other code
}
Массив должен быть сделан вне for
петля.
Вот пересмотренный Main
класс в полном объеме, комментарии должны довольно хорошо объяснить, что я сделал и почему.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//The strings here were unnecessary
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
in.nextLine(); //nextInt leaves a newLine, this will clear it, it's a little strange, but it makes sense seeing as integers can't have newlines at the end
//Make an array of Cars, the length of this array is limit
Cars[] cars = new Cars[limit];
//Iterate over array cars
for(int i = 0; i < limit; i++)
{
//Read all the properties into strings
System.out.println("Enter the number of Car Name - ");
String carName = in.nextLine();
System.out.println("Enter the number of Car Type - ");
String carType = in.nextLine();
System.out.println("Enter the Engine Type - ");
String engineType = in.nextLine();
//Set the object at current position to be a new Cars
cars[i] = new Cars();
//Adjust the properties of the Cars at this position
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
//We still have the variables from the scanner, so we don;t need to read them from the Cars object
System.out.println(carName+carType+engineType);
}
in.close(); //We don't need the scanner anymore
}
}
Закончив печатать это и понял, что вопросу два года:)