在 Java 中,如何使用循环来实例化新对象,将它们存储在数组中,然后使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13434003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:41:48  来源:igfitidea点击:

In Java, how do I use a loop to instantiate new objects, store them in an array, and then use them?

javaarrayssearchobjectloops

提问by art3m1sm00n

I have an introductory assignment for my CS class. I have a class named Car and a separate data file for later file redirection. I am to:

我的 CS 课程有一个介绍性作业。我有一个名为 Car 的类和一个单独的数据文件,用于以后的文件重定向。我要:

use a sentinel loop to read in the make, year, and price of each Car object, instantiate the object, and store it in the array carArr[]. For example, if you create a car object assigned to a variable named car1, you can just do: carArr[i] = car1 where "i" is an int counter. Also, count the elements of the array as they are stored in an int variable like "i" or numCars

使用哨兵循环读取每个 Car 对象的品牌、年份和价格,实例化该对象,并将其存储在数组 carArr[] 中。例如,如果您创建一个分配给名为 car1 的变量的汽车对象,您只需执行以下操作: carArr[i] = car1 其中“i”是一个整数计数器。此外,计算数组的元素,因为它们存储在诸如“i”或 numCars 之类的 int 变量中

Here is my code so far:

到目前为止,这是我的代码:

Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car [] carArr = new Car[SIZE_ARR];
int i = 0;
int numcars = 0;
String make = "";
int year = 0;
double price = 0.0;
final String SENT = "EndDatabase";

while (!scan.next().equals(SENT))
{
   make = scan.next();
   year = scan.nextInt();
   price = scan.nextDouble();
   Car car1 = new Car(make, year, price);
   carArr[i] = car1;
   i++;
   numCars++;
}

How do I create a new Car object each time I go through the loop and read in new data that doesn't have the same name? Do they need to have different names? As is, I'll just be making a bunch of objects all named car1. I will eventually have to print out the database and then read them in a new Car object as a search key. The key will then sequentially search through the carArr array. Will the search get confused because every element in the array is filled with an object of the same name?

每次我通过循环并读入不同名称的新数据时,如何创建一个新的 Car 对象?他们需要有不同的名字吗?照原样,我将制作一堆都命名为 car1 的对象。我最终将不得不打印出数据库,然后在一个新的 Car 对象中读取它们作为搜索键。然后该键将依次搜索 carArr 数组。搜索是否会因为数组中的每个元素都填充同名对象而变得混乱?

Also, when I go through to search the array and compare my stored objects to my search object do I just need to do:

此外,当我搜索数组并将存储的对象与搜索对象进行比较时,我只需要执行以下操作:

key.equals(carArr[i])

Will that compare the instance variables of each object to each other?

这会比较每个对象的实例变量吗?

In my Car class, I am required to have an accessor method for my year, make, and price instance variables. Where would I need to use these? It also states I have to have a "mutator method called setPrice" and "an equals method". Any idea what they mean for me to do in those? Sorry for the length of this and the multiple questions. I am just trying to stay ahead of my workload and my teacher isn't answering emails. THANKS!

在我的 Car 类中,我需要为我的 year、make 和 price 实例变量提供一个访问器方法。我需要在哪里使用这些?它还指出我必须有一个“称为 setPrice 的mutator 方法”和“一个equals 方法”。知道它们对我来说意味着什么吗?很抱歉这个长度和多个问题。我只是想保持领先于我的工作量,而我的老师不回复电子邮件。谢谢!

**********EDIT********************************************** I figured it out. Thanks!

**********编辑*************************************** ******* 我想到了。谢谢!

回答by Jon Skeet

My problem is how do I create a new Car object each time I go through the loop and read in new data that doesn't have the same name?

我的问题是如何在每次遍历循环并读入不同名称的新数据时创建一个新的 Car 对象?

Objects don't havenames.

对象不具有名称。

As is, Ill just I'll just be making a bunch of objects all named car1.

照原样,我只是制作一堆名为 car1 的对象。

No, you'll be creating a lot of objects, that's all. In each iteration, you'll assign a reference to a variable called car1, but a variable is notan object - and even the value of the variable isn't an object, it's a reference.

不,您将创建很多对象,仅此而已。在每次迭代中,您都会为名为 的变量分配一个引用car1,但变量不是对象 - 甚至变量的值也不是对象,而是引用。

It would be simpler to get rid of car1entirely though, and just assign the reference directly into the array:

car1完全摆脱会更简单,只需将引用直接分配到数组中:

carArr[i] = new Car(make, year, price);

It would be even better to use a List<Car>instead of an array - then you don't need to keep track of the size separately. I'd write the code as:

使用 aList<Car>而不是数组会更好- 这样您就不需要单独跟踪大小。我会把代码写成:

Scanner scan = new Scanner(System.in);
List<Car> cars = new ArrayList<Car>();

while (!scan.next().equals("EndDatabase"))
{
   String make = scan.next();
   int year = scan.nextInt();
   double price = scan.nextDouble();
   cars.add(new Car(make, year, price));
}

For the sake of the assignment you'll probably need to use an array, but that's just annoying...

为了分配,您可能需要使用数组,但这很烦人......

I'd also probably change the priceto be a BigDecimalinstead of double- you shouldn't use a binary floating point type for currency values.

我也可能将 theprice改为 aBigDecimal而不是double- 你不应该对货币值使用二进制浮点类型。

(Do you definitely want to discard the first value read in each iteration of the loop, by the way? All you're doing is checking whether it's EndDatabase- if it's not that, you're basically losing the information of whatever it was...)

(顺便说一下,你肯定要丢弃在循环的每次迭代中读取的第一个值吗?你所做的就是检查它是否是EndDatabase- 如果不是,你基本上会丢失它的信息...... .)