将对象存储到数组中 - Java
Storing object into an array - Java
我对 Java 比较陌生,我已经学习了一些简单的课程。我正在尝试模仿前一段时间的练习,但遇到了一些麻烦。
我有两个 class。一个是接收数据,另一个是存储数据。
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
如何将其存储到我在此 class 中创建的数组(不是数组列表)中:
public class CarDatabase {
Car[] carList = new Car[100];
public CarDatabase()
{
// System.out.println("test");
}
public void createAccount(String name, String color)
{
// this is where I am having trouble
for (int i = 0; i < carList.length; i++)
{
System.out.println("Successfully created: " + name +
"." + "Color of car: " + color);
break;
}
}
我还没有一个主要方法,但我稍后需要一个,例如,打印出这个数组,这是我无法解决的问题 - 我如何存储 DATA/OBJECTS 到 "CarDatabase" 数组中,以便我以后可以用它调用方法(而不是仅仅能够打印它)?
如有任何帮助,我们将不胜感激。
谢谢!
不太确定您要实现的目标,但我会试一试。
您可以像这样修改您的 CarDatabase
class -
public class CarDatabase {
Car[] carList = new Car[100];
int carsStored;
// No need for a constructor since we don't need any initialization.
// The default constructor will do it's job.
public void createAccount(String name, String color) {
carList[carsStored++] = new Car(name, color);
}
}
您的主要方法可能类似于 -
public static void main(String[] args) {
CarDatabase database = new CarDatabase();
database.createAccount("Lambo", "Red");
database.createAccount("Punto", "White");
// To loop through your database, you can then do
for(int i = 0; i < database.carList.length; i++) {
Car car = database.carList[i];
// Now you can call methods on car object.
}
}
希望对您有所帮助。
我对 Java 比较陌生,我已经学习了一些简单的课程。我正在尝试模仿前一段时间的练习,但遇到了一些麻烦。
我有两个 class。一个是接收数据,另一个是存储数据。
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
如何将其存储到我在此 class 中创建的数组(不是数组列表)中:
public class CarDatabase {
Car[] carList = new Car[100];
public CarDatabase()
{
// System.out.println("test");
}
public void createAccount(String name, String color)
{
// this is where I am having trouble
for (int i = 0; i < carList.length; i++)
{
System.out.println("Successfully created: " + name +
"." + "Color of car: " + color);
break;
}
}
我还没有一个主要方法,但我稍后需要一个,例如,打印出这个数组,这是我无法解决的问题 - 我如何存储 DATA/OBJECTS 到 "CarDatabase" 数组中,以便我以后可以用它调用方法(而不是仅仅能够打印它)?
如有任何帮助,我们将不胜感激。 谢谢!
不太确定您要实现的目标,但我会试一试。
您可以像这样修改您的 CarDatabase
class -
public class CarDatabase {
Car[] carList = new Car[100];
int carsStored;
// No need for a constructor since we don't need any initialization.
// The default constructor will do it's job.
public void createAccount(String name, String color) {
carList[carsStored++] = new Car(name, color);
}
}
您的主要方法可能类似于 -
public static void main(String[] args) {
CarDatabase database = new CarDatabase();
database.createAccount("Lambo", "Red");
database.createAccount("Punto", "White");
// To loop through your database, you can then do
for(int i = 0; i < database.carList.length; i++) {
Car car = database.carList[i];
// Now you can call methods on car object.
}
}
希望对您有所帮助。