将对象存储到数组中-Java [英] Storing object into an array - Java

查看:218
本文介绍了将对象存储到数组中-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java还是比较陌生,并且已经学习了一些简单的课程.我正在尝试模仿前一段时间做的练习,但遇到了一些麻烦.

I am relatively new to Java and I have taken some light courses on it. I am trying to emulate an exercise that I had a while back and I am having some trouble.

我有两节课.一种是获取数据,另一种是存储数据.

I have two classes. One is taking in data and the other is storing it.

public class Car{

public Car(String name, String color)
{
     this.name = name,
     this.color = color
}

如何将其存储到在此类中创建的数组(而不是数组列表)中?

How can I store this into the array (not an array list) that I created in this 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"数组,这样我以后可以调用它的方法了(而不是仅仅能够打印它)?

I don't have a main method yet but I will need one later on to for example, PRINT out this array and that is what I can't wrap my head around - how do I store DATA/OBJECTS into the "CarDatabase" array so I can call methods with it later (instead of just being able to print it)?

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thanks!

推荐答案

虽然不确定自己要实现的目标,但我会尽力而为.

Not really sure what you are trying to achieve but I'll give it a go.

您可以像这样修改 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);
  }
}

您的主要方法可能类似于-

And your main method could look like -

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆