I have an ArrayList of Objects. The Objects are flowers. After adding flowers to a list of flowers, I want to print out each flower's name. Whenever I add a flower, I give the flower a name. Say I add three flowers named "Rose", "Tulip", and "Daffodil". When I run my function that iterates through the ArrayList, all I get is three Daffodils. If I add five flowers, it displays five flowers but all of them have the name of the last flower I added. Here is my main class:
import java.util.Scanner;
import java.util.ArrayList;
public class mainClass {
static ArrayList<flowerClass> flowerPack = new ArrayList<flowerClass>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(true){
System.out.println("1. Add flower to flowerpack.");
System.out.println("2. Display the flowers in the flowerpack.");
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower();
break;
case 2:
displayFlowers();
break;
}
}
}
public static void addFlower(){
Scanner input = new Scanner(System.in);
System.out.println("What is the flower's name?");
String flowerName = input.nextLine();
flowerPack.add(new flowerClass(flowerName));
}
public static void displayFlowers(){
for (Object o: flowerPack){
System.out.println(flowerClass.getName());
}
}
}
Here is my flowerClass:
public class flowerClass {
public static int numberOfFlowers = 0;
public static String flowerName = null;
static String flowerColor = null;
static int numberThorns = 0;
static String flowerSmell = null;
flowerClass(String desiredName){
flowerName = desiredName;
numberOfFlowers++;
}
public static void setName(String desiredName){
flowerName = desiredName;
}
public static String getName(){
return flowerName;
}
}
I have tried using an array of objects instead of an ArrayList. I can get it to display the unique address of each separate flowerClass object but I can never successfully access each object's flowerName to display it to the user. Thanks for any suggestions.