Reputation: 93
I have an array list of Fleets (Each fleet will hold its own list of Trucks).
I have a fleet class with the constructor
public Fleet(String businessName){
this.businessName = businessName;
this.fleetList = new ArrayList<Truck>();
}
So:
In my TUI, I have a helper method called createFleet. When the user presses 1 on the menu, it asks for a name of his business, and then makes a fleet named that. That method is:
public static void createFleet(){
System.out.println("");
System.out.println("Please enter the name of the fleet.");
inputText = scan.nextLine();
fleetCollection.add(new Fleet(inputText));
printFleets();
System.out.println("");
System.out.println("--- Fleet: " + inputText + " added ---");
System.out.println("");
}
And my problem is that when I add one Fleet, and print the results I get:
Fleet 0: Fleet Number One
But when I add Fleet Number One, then press 1 on the menu again to add ANOTHER fleet (named Fleet Number Two) and print the fleet list, the results are:
Fleet 0: Fleet Number Two
Fleet 1: Fleet Number Two
It seems to be confusing the two...and this further breaks the program when I try to add trucks to the fleet, because It cannot pick the "right" fleet.
Please let me know if you need any other of my code. I just need this to correctly add and print the fleets in the fleet list:
private static ArrayList<Fleet> fleetCollection;
Thank you :) for all the help!
Upvotes: 0
Views: 178
Reputation: 4180
have you overridden the equals method in Fleet ? if so and it's not correct, it could be the cause of your weird result
Upvotes: 2
Reputation: 25146
You need to be clear about use of static
static variable
<class-name>.<variable-name>
static method
<class-name>.<method-name>
this
" or "super
" keywords in anywaysrc : http://www.javatutorialhub.com/java-static-variable-methods.html
Upvotes: 3
Reputation: 11228
I made small modifications to your program to make it simple.
class Fleet{
String businessName;
public Fleet(String businessName)
{ this.businessName = businessName;}
public String getBusinessName()
{
return businessName;
}
}
public class T {
private static ArrayList<Fleet> fleetCollection = new ArrayList<Fleet>();
public static void main(String[] args)
{
createFleet("A");
printFleets();
createFleet("B");
printFleets();
}
public static void createFleet(String name){
System.out.println("");
fleetCollection.add(new Fleet(name));
}
public static void printFleets(){
Iterator i = fleetCollection.iterator();
Fleet f;
while(i.hasNext())
{
f = (Fleet)i.next();
System.out.println(f.getBusinessName());
}
}
}
It prints as expected.
A
A
B
Check your access modifiers on "businessName" field. It shouldn't be static. Also check printFleets() method.
Upvotes: 1
Reputation: 12054
You probably declared businessName
in Fleet class static
, if so then remove it
Upvotes: 3