我对Java比较陌生,并且已经学习了一些简单的课程。我正在尝试模仿前一段时间做的练习,但遇到了一些麻烦。
我有两节课。一种是获取数据,另一种是存储数据。
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
如何将其存储到在此类中创建的数组(而不是数组列表)中:
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;
}
}
我还没有主要方法,但是以后需要一个方法,例如,打印该数组,这就是我无法解决的问题-如何将数据/对象存储到“ CarDatabase”数组中所以我以后可以用它来调用方法(而不仅仅是能够打印它)?
任何帮助,将不胜感激。谢谢!
不太确定您要达到的目标,但我会尝试一下。
您可以CarDatabase
像这样修改您的课程-
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.
}
}
希望能有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句