while(!input.equals("-1")){
plantName = "";
plantCost = "";
colorOfFlowers = "";
isAnnual = false;
if (input.charAt(0) == 'p') {
Plant plant = new Plant();
String[] temp = input.split(" ");
plantName = temp[1];
plantCost = temp[2];
plant.setPlantName(plantName);
plant.setPlantCost(plantCost);
myGarden.add(plant);
}else {
Flower flower = new Flower();
String[] temp = input.split(" ");
flower.setPlantName(temp[1]);
flower.setPlantCost(temp[2]);
flower.setPlantType(Boolean.parseBoolean(temp[3]));
flower.setColorOfFlowers(temp[4]);
myGarden.add(flower);
}
input = scnr.nextLine();
}
这是一个例子来说明我的意思。在 if 语句的开头,我创建了一个工厂对象,它最终使程序按照我想要的方式工作,我只是不太确定它为什么工作。我的想法是,通过在 while 循环内创建对象,它会在循环结束时“删除”并创建一个新对象。
尽管我不确定,因为每次我向教授询问有关任何概念的问题时,他都会告诉我到这里来问别人。 提前致谢。
最佳答案
您正在保存一个副本,以便旧对象被覆盖。
Object[] a = new Object[10];
for (int i = 0; i < 10; i++) {
// ob gets copied over with the new object
Object ob = new Object();
// but it is saved here
a[i] = ob;
}
和这个没有什么不同。
int[] n = new int[10];
for (int i = 0; i < 10; j++) {
int x = i*10;
n[i] = x; // x is saved in array.
}
关于java - 如果要在循环中创建一个对象,它会在每次迭代中不断重新创建该循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61691317/