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.
Related
Problem
I want to know if this is possible if I could create a State machine that would contain all the methods and the Values of MethodById would be stated in the machine.
P.S. this is my first question ever on here. If I do it wrong I'm sorry but that is why.
Description (TL;DR)
I'm trying to cross reference data about Sales representatives. Each rep has territories specified by zip-codes.
One dataset has the reps, their territories and their company.
Another data set has their names, phone number and email.
I made a Sales-rep class that takes from the first data-set and needs to be updated with the second data-set.
I also need the Sales-reps to be put in a look-up table (I used a hashmap for this) of <key: zip code, value: Sales-rep object>.
What I want is for each Sales-rep object to having an ID that is standard across all my datasets. I can't use the data I'm provided with because it comes from many different sources and its impossible to standardize any data field.
Names, for example, are listed so many different ways it would be impossible to reconcile them and use that as an ID.
If I can get an ID like this (something like an SSN but less sensitive) then I want to try what my question is about.
I want to iterate through all the elements in my <key: zip code, value: Sales-rep object> hashmap, we will call it RepsByZipCode. When I iterate through each Salesrep object I want to get an ID that I can use in a different hashmap called MethodById <key: ID, value: a method run on the Object with this ID>.
I want it to run a different method for each key on the Object with the matching key (AKA the ID). The point is to run a different method on each different object in linear time so that by the end of the for loop, each object in RepsByZipCode will have some method run on it that can update information (thus completing the cross-referencing).
This also makes the code very extendable because I can change the method for each key if I want to update things differently. Ex:
//SalesRep Object Constructor:
SalesRep(String name, String email, ..., String Id)
Map<String zipcode, Salesrep rep> RepsByZipCode = new HashMap<>{}
//code fills in the above with the first dataset
Map<String ID, ??? method> MethodById = new HashMap<>{}
//code fills in the above with the second dataset
for(String ZipKey:RepsByZipCode){
Salesrep Rep = RepsByZipCode.get(ZipKey);
Rep.getId = ID;
MethodById.get(ID);
//each time this runs, one entry in RepsByZipCode is updated with one
//method from MethodById.
//after this for loop, all of RepsByZipCode has been updated in linear time
You could put these methods into different classes that implement a common interface, and store an instance of each class in your map. If you're using at least Java 8 and your methods are simple enough, you could use lambdas to avoid some boilerplate.
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.
I got an assignment in which I have to make a phone book using a link list.
In this list I got to be able to add an entry. The entry must have a person first name,last name and phone number.
I have to be able to delete the first,last, and phone number of the entries.
How can I do this I am think of creating a class named entry with string for first,last,and phone number.
And when the user decides to create a new Record put a new Object entry with these fields. Into the link list.
The problem is how can I create a new Object and name it when the user want to put it on the list.
I cannot keep using the same name for an object over and over or can I?
You can't.
Suppose you have a class, Person, with properties as you suggested. directory is an object of type LinkedList<Person>. The correct way to do what you are trying to do is to make Person immutable. Every time you want to add a Person, you write statements such as directory.add(new Person("George", "Washington", "1776")) (the constructor initializes final Strings.
You must make new objects because LinkedList only stores references to objects, not copies of them.
Really, though, you can instead of Person use an associative array, for example mapping enum types for properties to strings.
Make a list of some kind (array, ArrayList, whatever floats your boat) and store it there using new Record(...).
Making a class for keeping the data is a good way to solve the problem.
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...
My problem is to store details of people in Java. I looked up at the Oracle website topic How to Use Tables and found out that one can use object arrays(2 dimensional) to store details.
But my interest is to make a dynamic object array so I can store any amount of data and also take input to store those details from the user. For instance, at the beginning of the program I can specify an object array to hold 5 records, but I actually want an array that could add another available location if I need to add more records (dynamic).
Is there a way this is possible in java ? If so, do you happen to know any good places I could start, perhaps a link. Is storing using an Object array the best option?
An array holds homogenous data, i.e. usually the class of everything in every cell of an array is the same. You will likely not want to store a person's name and his shoe size in fields of the same type, so... let's drop one of the array's dimensions. You should declare a class called something like Person and specify within it all the attributes you want to store for a person. Having done that, you will only be wanting to store a one dimensional array (or something) of Person.
Next, note that arrays are fixed in size. If you want to extend an array, you would need to allocate a new, bigger array, copy the contents of the old one into the new one and then go on working with the new one in place of the old one.
That's a lot of work, and error prone. In the modified words of Apple, there's a class for that! The older qualified class was Vector, a class where you could store objects and that would grow every time you add a new object to it. Nowadays, the class to use for this (it's a bit more efficient) is ArrayList. Same thing: You do
ArrayList<Person> myList = new ArrayList<Person>();
and then you can repeatedly
newPerson = new Person("Bruce", "Wayne", 1972, "Gotham City");
myList.add(newPerson);
and you can access folks in the list by doing
int personNumber = 0;
Person retrievedPerson = myList.get(personNumber);
or even
for (Person someone : myList) {
System.out.println(someone);
}
EDIT
OK, to store people with an ID and access them by that ID assuming the person ID is an integer, some appropriate code would be:
TreeMap<Integer, Person> myMap = new TreeMap<Integer, Person>();
newPerson = ...
myMap.put(newPerson.getId(), newPerson);
then you can retrieve it with
Person p = myMap.get(id);
Look at java.util.List, java.util.Map, and System.arraycopy for some data structures that will help you.
First you should understand that the Object array passed to the JTable won't get stored. It just be used to display the records of what you've done. To store the values you've got, you have to use Files or DB.
You can set Object array size dynamically in a way that you should know how many records you really need to show. I think with JDK 1.6 you can't dynamically change the size of the Array, but the upcoming JDK 7 may provide such a feature.