I have a bunch of strings with weird names (like this docFileeh934fhry) that contain text like this
System.out.println(docFileeh934fhry);
`.............document: 12345.....
...................
...............`
I want to rename these strings. So that the above string will be String doc12345
How can I do this?
I know how to get this number using Pattern.compile
Let's say I have this number String docNumber = "12345";
Now how can I dynamically create a new string?
I tried
String doc+docNumber = docFileeh934fhry; // no result
You might be able to do this with reflection, but it has to be said that this is a very poor approach.
Your naming of variables should not depend on any external input. Instead, give it a name that describes its contents and go from there.
What do you gain by naming it doc1?
If you are looping trough files all you probably want is a currentDocument. Any other variables (firstDocument, nextDocument, oldDocument, etc) you name according to their function, not their contents.
If you want a way to uniquely identify the correct document, create a class instead
class Document {
int id;
string contents;
}
After storing all these Document objects into a collection (like an ArrayList), you can just retrieve the document you need on basis of that id rather than having to mess around with a bunch of generated variables.
Another point to note: how would you even use this when you have 50 documents? 100? 10.000? This would be impossible to maintain.
If you don't want to create a custom class you can go with the HashMap<Integer, String> route.
This isn't how Java works. If you want to associate an object with a String, then use a Map such as a HashMap<String, String>.
Assign the string to the variable w/ the new name. Note that the new name will have to be have been defined when writing the code, it can't be computed on the fly (if that is what you are driving at).
You can't use + in a variable name. As above, you can't make variable names on the fly.
Here maybe one possible solution,use Hashmap,key is your varname(the way as you wish) and value is your string.
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.
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.
Good Afternoon,
i would like to ask regarding the methods to use string as reference.
Let say, that i got two object of type LinkedList named ChinaShip and HongkongShip
Normally, if i wanted to access a method (for example getFirst())
i will type ChinaShip.getFirst()
Now, let say that in other object, i got a variable Destination which content is a String.
The example of the Content will be China and Hongkong
Is it possible to use the content of the variable as the name for accessing the LinkedList object?
my approach first would be concatenate the variable first, which will be Destination + "Ship"
This will produce a string which is ChinaShip and HongkongShip
The reason i'm doing this way rather than comparing the string is that the Destination consist of hundreds of posibilities.
Thank You Very Much.
Regards,
Unfortunately you can't do that in Java. But this is closer with that:
HashMap<String, LinkedList> dest = new HashMap<String, LinkedList>();
dest.put("China", ChinaShip);
dest.put("Hongkong", HongkongShip);
.....
if(dest.containsKey(Destination){
dest.get(Destination).getFirst();
}
You can use the reflection API. If the lists are declared in the class MyClass you can use the following code:
LinkedList list = (LinkedList) MyClass.class.getDeclaredField(Destination + "Ship").get(this);
This assumes that the above code is called from within a MyClass object, otherwise the get(this) call must be changed to get(myClassInstance). Though as MadProgrammer mentions, you might be better of using a Map.
You can use a Map and use the desitnation string as your key because these will be unique:
Map<Desitnation, value> destinations = new HashMap<Desitnation, value>();
then search through the Map for your destination key:
http://www.tutorialspoint.com/java/util/hashmap_get.htm
I think you need to re-work your architecture. You shouldn't have to create method names from Strings.
It seems to me like you need a Ship object which has a destination, and a linkedlist of Ships.
If you need to map ships by destination, what you can also do is have a Map where they key is the destination string, and the value is the linked list of ships going to that destination.
So if you do a map.get("China") you will get a list of ships going to China, and from there you can do what you want.
Suppose I have, for example, an array of objects generated by parsing a document. These objects look like this:
Object{
id
text
anotherProperties
}
The first two attributes (id and text) are set during parsing, but now I want to add another Properties(additional attributes), which can't be set during parsing, because it is too complicated to determine them, but depends on text.
How can I achieve this in an elegant way?
In Java?
Thanks for responses
Perhaps use a HashMap with key of Integer (your id) and a value of DocProperites which consists of text and anotherProperites.
Then when you are ready to set anotherProperties you can retrieve the object from the HashMap and then set it.
For example
Map<Integer, DocProperties> map = new HashMap();
and DocProperties is
public class DocProperties {
private String text;
private String anotherProperties;
//plus the usual setters, getters and ctor
}
then when you want to set the anotherProperties you can call
map.get(key).setAnotherProperties(....);
If you wanted something more dynamic then you could use another HashMap instead of DocProperties. The HashMap could then have keys added and removed as you parse. I wouldnt advise this though as the code could become very messy and bug ridden.
I have some data that looks like this
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
myobject{keyone:"valueone",keytwo:"valuetwo",keythree:"valuethree"}
And I'm wondering what the best way to create a bunch of objects from it would be. I've written the following regex to extract all the values from a particular Key...
Pattern p_keyone = Pattern.compile("keyone:\"(.+?)\"\\,");
Matcher match_keyone = p_keyone.matcher(string);
while(match_keyone.find()) {
myobjects.add(new MyObject(match_keyone.group(1));
}
Which gives me a bunch of objects with a single argument...
myobjects.add(<valueone>);
Is there a way I can execute a single regex query and create a bunch of objects with all the values as arguments in one go. Like this...
new MyObject( <valueone>, <valuetwo> , <valuethree> );
Thanks
Your approach is not bad.
Few things you could change, though it depends on your requirements whether they make sense:
Create a "Factory" class which takes 1 line of data and creates the object.
Read the data line by line, for each line use the Factory to create it.
Depending on how fancy (and error-prone) you want it to get, you could even read the names of the objects and properties and then use reflection to create instances and set the properties.
String.split() could help:
String line = "myobject{keyone:\"valueone\",keytwo:\"valuetwo\",keythree:\"valuethree\"}"
// ^-----[0]------^ ^--[1]-^ ^--[2]-^ ^--[3]-^ ^--[4]---^ ^--[5]---^ ^[6]
String[] parts = line.split("\"");
MyObject myObject = new MyObject(parts[1], parts[3], parts[5]);