I'm programming in java for a class project.
In my project I have airplanes, airports and passengers.
The passenger destination airport is randomly created, but then I have to add it to a List with passengers for that destination.
As long as the airports are read from a file thus they can vary, how can I create Lists according to these airports?
What I want to do is something like:
List<Passenger> passengersToJFK = new ArrayList<Passenger>();
.
.
.
if(passenger.destination == "JFK"){
passengersToJFK.add(passenger);
}
The problem is that as I've said, the number and name of airports can vary, so how can I do a general expression that creates Lists according to the Airports File and then adds passengers to those Lists according to the passenger destination airport?
I can get the number of Airports read from the file and create the same number of Lists, but then how do I give different names to this Lists?
Thanks in advance
You can keep a registry of the associations between a destination or airport and a list of passengers with a Map, in a particular class that centers this passengers management.
Map<String,List<Passenger>> flights = new HashMap<String,List<Passenger>>();
Then, whenever you want to add a new destination you put a new empty list and
public void addDestination(String newDestination) {
flights.put(newDestination, new ArrayList<Passenger>());
}
When you want to add a passenger, you obtain the passenger list based on the destination represented by a String.
public void addPassengerToDestination(String destination, Passenger passenger) {
if(flights.containsKey(destination))
flights.get(destination).add(passenger);
}
I suggest you dig a little deeper into some particular multi-purpose Java classes, such as Lists, Maps and Sets.
I would probably create a Map of airports with airport name as the key and a List of passengers as the value.
e.g.
Map<String, List<String>> airports = new HashMap<String, List<String>>();
airports.put("JFK", passengersToJFK);
You sound like you're thinking too much in terms of primitives, Strings, and collections and not enough in terms of objects.
Java's an object-oriented language; start thinking about Objects and encapsulation.
You've got a good start with your Passenger class. Keep going with Airport.
Do you add Passengers to Airport? Nope, I think they belong to a Flight.
Do a little thinking about your problem before you write more code.
You shouldn't focus on giving the actual variables of list objects unique names, but instead, create a map from String (destination id) to List (passengers heading to that destination), and add lists on the fly to that map, linking each new list to its relevant destination. Update the lists in that map as needed.
The best way to do it is to create objects for all three.
You might have an Airport object that looks like this:
class Airport{
String name;
List Airplane airplanes;
}
then you would have an airplane that looked like this:
class Airplane{
String name; // ?? or bodyType? or whatever else you need
List Passenger passengers;
}
In this way you compose your objects from each other in a way that ends up being much easier to understand and deal with.
Note that I'm leaving off methods, like Airport probably has a method like "addAirplane" to add another airplane, and the airplane object has an addPassenger method...
Related
I have some data of let’s say type Person. This Person has a phone-number property but also a calling and a called phone-number properties.
class Person {
String id;
String displayName;
String phoneNr;
String callingNr; // or List<String> callingNrs;
String calledNr; // or List<String> calledNrs;
}
What I want, is I put a bunch of those Person objects in a Graph instance and than render the relationships on a view. Ideally the components drawn on the view are interactive, meaning you can click on a node/vertex that highlight the edges (and maybe more).
I tried JUNG, but in the documentation, I see some examples that I have to, kind of, define the relationships between Person objects myself, like below:
Graph.addEdge("edge-name", personA.phoneNr, personB.phoneNr);
I’m new to JUNG, but maybe there’s a way to tell JUNG about the properties of Person and that JUNG knows how to connect them?
Is this possible with JUNG? Or do I need another type of library, if yes, than can someone please provide me one I can use?
Here is what I would do:
Make a java.util.Map of each person's phone number (key) to an instance of the Person (value). That is your reverse number lookup.
Populate your reverse number lookup map by iterating over your collection of people using the PhoneNr as the key and the Person instance as the value.
Next, I would create an edge class 'PhoneCall' that contains information like 'time of call' and 'duration of call' (more or less info, depending on what you have available).
To add edges to your graph, iterate over your collection of Person instances, and for each Person, iterate over the collection of calling numbers. For each calling number, use the reverse number lookup map to get the person calling and make a directed edge to connect the calling person to the current person.
Do something similar for the each Person's collection of called numbers.
Your graph nodes will be Person instances, and your edges will be PhoneCall instances that connect one Person to another. Be sure to add an equals and hashCode method to your Person class and to your PhoneCall class so that they will work properly (and duplicates will be detected and hopefully ignored).
Hope this helps!
I am creating a game in Java and need to create a list of all of the rooms in it.
I have a 'Rooms' class that has the code for the room, i.e. room name, items in the room etc.
In the Room class I want to have a static ArrayList that has all of the room objects in the whole game in there. This is needed for a method I am working on.
I have created an ArrayList field:
private static ArrayList<Rooms> listOfRooms = new ArrayList<Rooms>();
In the initialisation of each instance of Rooms, I wish to add that instance to the listOfRooms ArrayList.
I assume you start with listOfRooms.add(), but what would you actually put in the parameter to add the current object to the list of Rooms objects?
You'd add this to the list; this being a reference to the current object (a Room in this case) being worked on:
listOfRooms.add(this);
Note though, having listOfRooms as a static member of the class is a bad idea. With this setup, you can only ever have one list, and anyone can alter the list however they want since it's public.
It would likely be much better to create something like a Hotel class and make it a member of that:
class Hotel {
ArrayList<Rooms> listOfRooms = new ArrayList<Rooms>();
}
Now you can at least have multiple hotels if necessary with separate lists of rooms, and to modify the rooms, code would at least require a reference to the hotel.
Adding to what Carcigenicate said, it's always better to have more abstraction in object oriented programming.
For example, Hotel object has a Floor ArrayList in it. Each Floor object contains ArrayList of Room and so on.
I was hoping someone could tell me if I'm even going about this the right way, or if what I'm doing is even possible.
My end goal is to create a program where you can create cabins, create campers, and assign them to a cabin.
What I thought of was allowing the user to create a new ArrayList by having a method called that does such. I would create a Camper class where it has the variables such as name, age, gender, etc...
Then I would write a method that looked something like this....
public static void userCreatesList(){
ArrayList<Camper> cabin = new ArrayList<Camper>();
}
The problem is, the method works when I add items to the list and have it print out as each time it prints a different list when calling the method, however, what I cannot figure out how to do is to call a previous list again as every list here will have the same variable or object name.
So, if I created say three cabin lists all together by calling this method three times, how would I assign a person to a particular cabin if they all end up having the same variable name?
It has to be a program where the user can create the list and I didn't have to declare a number of lists with a different variable name, because each camp may have a different number of cabins, and they have to be able to make their own list?
If what I'm doing is not possible and I need to be using another type of object besides a list to do this, please just tell me and I'll research how to use that object.
I've searched all over how to create a new group, a new set, etc.. and I cannot find anything relevant to what I'm trying to do that can explain this.
I want them to be able to give that group a name, such as "Red Cabin", "Blue Cabin", "Cabin 1", "Cabin 12", etc....
For this I would recommend to use Map, with group name as a key and ArrayList as value.
private static Map<String, ArrayList<Camper>> cabinMap = new HashMap<String, ArrayList<Camper>>();
public static void userCreatesList(String groupName){
ArrayList<Camper> cabin = new ArrayList<Camper>();
cabinMap.put(groupName, cabin);
}
Later you can access to the certain group from this map by name and add members to it.
starting out with Java and have run into some issues.
I have created a class called: Admin, which a user will give attributes to such as a name and other pedigree info...but the main function of the Admin class is to create arrays that will be used as a queue system.
I am trying to allow the Admin to create as many arrays as they desire. However I am having trouble figuring out a way to differentiate between each of the arrays when it comes to reiterating them back to the user.
For instance, lets say an "Admin" was a Bank and wanted to create an array that a "User"(i.e. customer, which has it's own class) could join to get in line to see a teller.
The Bank may also want to create a line for a "User" to see a Loan Officer, etc.
I am not able to allow the Admin to give each array a specific reference variable that would differentiate it from others by doing this:
System.out.println("Enter the name of the line you wish to create: ");
String lineName=keyboard.nextLine();
ArrayList<User>lineName=new ArraryList();`
The program gives an error saying that the variable has already been initialized in the method when I do so, which I kind of understand. However having the functionality of knowing what line I am looking at within the code is invaluable to me.
Another reason I wish to do this is because I want to create an Array of Arrays that would show a customer all of the "lines" they could potentially join. So I would like the output to look something like this:
John Hancock Bank lines:
Teller Window
Loan Officer
Mortgage Specialist
etc.
From there I would allow the user to access the element of the array they wish to join.
What would be the best way to "identify" each specific array that is created by an Admin?
Typically, variable names have meaning to a programmer, and not to a user.
If you want to associate a list with a name, you'd either want to use a Map like so:
Map<String, ArrayList<String> lines = new HashMap<String, ArrayList<String>>();
lines.put(keyboard.nextLine(), new ArrayList<String>());
Or create a new class to model this association:
class Line{
String lineName;
ArrayList<String> people;
public User(String name, ArrayList<String> people){
this.lineName = name;
this.people = people;
}
}
The comments are above are right though. I think a Queue would be better for your purpose.
You could use a HashMap.
Map<String, List<User>> map = new HashMap<String, List<User>>();
System.out.println("Enter the name of the line you wish to create: ");
map.put(keyboard.nextLine(), new ArraryList<User>());
The error about the you're getting about the variable that has already been initialized is due to you reusing a variable name as follows:
String lineName=keyboard.nextLine();
ArrayList<User> lineName=new ArraryList();`
You have created two variables but they have the same name. Each variable must have an unique name - otherwise when you later refer to lineName there's no way to know if you mean the String or the ArrayList.
As other have noted, in general when you want stuff like a "line" that has a "line name" and a value, the correct data type to store this information is a map. A map consists of key-value pairs, where the key is the "line name" and the value is the actual data.
You'll notice people putting a lot of emphasis in choosing the correct data type and structure for storing your information. This is a very core concept in programming: choosing the correct data structure and type to use is extremely important in producing effective and good code and it's best to grasp these concepts well from the get-go.
So right now I'm writing a program that will take a user input such as:
"Jeff" for a first name
"Henderson" for a last name
a phone number with them
an amount to be stored in their bank account
And store it all into a Linked List.
If I were to add another person with this similar info, how would that be stored in the link list such at I could access both individuals information separately?
Right now I'm using this to establish all the storage when entering a new user:
private final Scanner keyboard;
private final LinkedList<String> firstName;
private final LinkedList<String> lastName;
private final LinkedList<String> teleNumber;
private final LinkedList<String> accountBalance;
public bankdata()
{
this.keyboard = new Scanner(System.in);
this.firstName = new LinkedList<String>();
this.lastName = new LinkedList<String>();
this.teleNumber = new LinkedList<String>();
this.accountBalance = new LinkedList<String>();
}
I plan to use keyboard.next(); to read the user input and then use an add method I've written to store the information into each linked list.
The way it is set up is that there is a Linked List for every single object variable like:
a Linked List for first name
a Linked List for the last
a Linked List for the tele number
a Linked List for the account balance
If I want to call information associated with one specific person, how do I have it so when I request that users information that I can see all his stuff if they're in another linked list?
The thing here is to create your own data structure. I'd say research a bit more about LinkedList. Almost every linked list example online can help you out.
Hint: Create a class for your node, and store all information pertaining to each person in that node.
EDIT: Just to complete the answer: How do I create a Linked List Data Structure in Java?
EDIT 2: Based on your edited OP, I think you want to have 4 LinkedLists, and find all information for one person. I'll assume you are going to search by the person's name (if not, the process is stil the same). Also, it is assumed that information for one person is stored at the correct corresponding node. So, person1 has all information in first nodes of all 4 lists, person2 has all nodes at "index" 1.
So, you start searching the LinkedList storing names, and stop as soon as you find the name (or throw an error if not found). Also keep track of the number of nodes you have seen. This will be the index you need to get information for all other Lists.
Now, using for loop, traverse appropriate number of times on each of the rest 3 Lists, and return the value encountered.
It would be easier to group all that data in a class and then use a Hashtable as your data structure, you should find many resources online about Hashtable's also check out http://javarevisited.blogspot.com/2012/01/java-hashtable-example-tutorial-code.html. About obtaining input..you can store it in an array since the number of variables is fixed then use Arrays.toList() to cast it into a list and perhaps use a switch inside the loop to initialize your variables. note that there are alternatives to the hashtable structure but i recomend since you want to retrieve your data later and it might get large.
This is a typical Primitive Obsession.
You should use an Object to save the data. It would be more flexible and easy to use.