To use a string value as a variable name [duplicate] - java

This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 6 years ago.
Is it possible to use String as a variable name.. like in this example -
String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");
if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}

What you can do is by associating (mapping) those values to the Music object. Here is example:
Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));
if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}

You can't do this in Java, but you can almost do it using a map.
Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);
if(map.get(musicPlaying).stillPlaying) {
// happy listening
}

No, this is not supported in Java.
stillPlaying doesn't exist as a method (or variable) on String.
As the comment suggests below, it probably is doable through some reflection, however to quote another comment...
You can do all kinds of stupid tricks with reflection. But you're
basically breaking the "warranty void if removed" sticker on the class
the instant you do it.

No. But you might want to look into using a Map instead.

I used a switch case.
Switch (string)
{
case "string1":
string1();
break;
case "string2":
string2();
break;
}

Related

Java - Remove "Optional" from a variable (convert)

for a piece of homework, I have to set a variable. The set method given to me, converts that into "Optional". However, I have to store this variable in an ArrayList which doesn't allow Optional variables.How can I convert the variable so it is no longer Optional?
The set method:
public void setParentVertex(IVertex<T> parentVertex)
{
if(parentVertex == null)
this.parentVertex = Optional.empty();
else
this.parentVertex = Optional.of(parentVertex);
}
Where I'm trying to use it:
ArrayList<IVertex<T>> path = new ArrayList<IVertex<T>>();
IVertex<T> parent = current.getLabel().getParentVertex();
path.add(parent);
The error I keep receiving is: "Error: incompatible types: Optional> cannot be converted to IVertex" due to the line where I declare the variable "parent".
Thank you.
Here is the correct version
List<IVertex<T>> path = new ArrayList<IVertex<T>>();
current.getLabel().getParentVertex().ifPresent(path::add)
Also it would be good to rewrite setParentVertex function:
public void setParentVertex(IVertex<T> parentVertex) {
this.parentVertex = Optional.ofNullable(parentVertex);
}
I think you don't have to add it to your list, if there is no value. So just do
if(nameOfOptional.isPresent()){
list.add(nameOfOptional.get());
}
First, add a check to find the value is present or not (by calling isPresent()) and then if the value is present then add to your ArrayList path object as shown below:
ArrayList<IVertex<T>> path = new ArrayList<>();
Optional<IVertex<T>> parent = current.getLabel().getParentVertex();
if(parent.isPresent()) {
path.add(parent.get());
}
or the shorter form is shown below which uses ifPresent method:
ArrayList<IVertex<T>> path = new ArrayList<>();
Optional<IVertex<T>> parent = current.getLabel().getParentVertex();
parent.ifPresent(path::add);
Also, I suggest you have a look at the Optional API methods here.
As a side note, I recommend you to use diamond <> operator while declaring generic types (like shown above i.e., new ArrayList<>()) , so that your code will be less verbose.

how to get a component by name in java [duplicate]

This question already has answers here:
Get a Swing component by name
(8 answers)
Closed 6 years ago.
here is the edited code with specified method.
String value = obj.validateTextFields(txtFields);
public String validateTextFields(JTextField[] txtField){
String res = "";
for(JTextField txtFields : txtField) {
if(txtFields.getText().equals("") ) {
JOptionPane.showMessageDialog(null, txtFields.getName() +" is empty!");
res +=txtFields.getName()+",";
}
}
return res;
value is the names of text fields so how to get the text field by this name.
If you want to associate an object with a String for easy retrieval, one simple way is to use a Map<String, JTextField> with a concrete implementation as a HashMap<String, JTextField>.
Then in your initialization code, you place the components in the map with their associated String using the Map's put(...) method, and later when you want to retrieve it, use the Map's get(...) method.

How to find an object in arraylist by one of it's element and print it? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am developing a console application where I can register items. Each item has 3 properties serial number, model, year.
I have 3 classes Laptop, Laptops(arraylist) and Office to run the application.
So far I have managed to find the object itself by index number, but i need to list all objects with the property typed in.
This is how I ask user to choose the option
Laptops inHouse = new Laptops();
model = Console.askModel("Enter Model : ");
inHouse.findModel(model);
break;
That is the find method in Laptops class
public void findModel(String aModel)
{
int arraySize = laptops.size();
for(int i=0; i<arraySize; i++) {
if (laptops.get(i).getModel() == aModel) {
System.out.println(laptops.get(i));
}
}
}
this is the askModel method in Console class.
public static String askModel(String aModel)
{
System.out.println(aModel);
String model = askString("Enter the model: ");
return model;
}
Additionally, I am quite new to java, I understand the concept but still struggling on many thing so If I forgot to post a code which is needed to solve the problem I am sorry in advnace.
findModel is fine except for your String comparison which checks for object equality instead of String equality, change the comparison to:
if (laptops.get(i).getModel().equals(aModel))
For non-primitives, equality tests using == check if the object is literally identical (that it's the same instance), whereas String.equals will compare the actual String value.
You might want a HashMap instead of an ArrayList:
import java.util.HashMap
public class Laptops{
Map<String, Laptop> laptops = new HashMap<String, Laptop>();
//alternatively if java 7, do "= new HashMap<>();" instead
public Laptop findModel(Laptop aModel){
Laptop theModel = laptops.get(aModel);
return theModel;
}
To put the models in, you'll use the put method of HashMap:
public void addAModel(String modelName, Laptop aModel){
laptops.put(modelName, aModel);
}
This way if you know a model's name (a String), it will return you the Laptop object you're after.

Determining a String based on the value of another String?

Not all that sure how I would describe this question, so I'll jump right into the example code.
I have a Constants.java
package com.t3hh4xx0r.poc;
public class Constants {
//RootzWiki Device Forum Constants
public static final String RWFORUM = "http://rootzwiki.com/forum/";
public static final String TORO = "362-cdma-galaxy-nexus-developer-forum";
public static String DEVICE;
}
In trying to determine the device type, I use this method.
public void getDevice() {
Constants.DEVICE = android.os.Build.DEVICE.toUpperCase();
String thread = Constants.(Constants.DEVICE);
}
Thats not correct though, but thats how I would think it would have worked.
Im setting the Constants.DEVICE to TORO in my case on the Galaxy Nexus. I want to then set the thread String to Constants.TORO.
I dont think I'm explaining this well, but you shoudl be able to understand what I'm trying to do fromt he example code. I want
Constants.(VALUE OF WHAT CONSTANTS.DEVICE IS) set for the String thread.
Another way to put it,
I want to get Constants.(//value of android.os.Build.DEVICE.toUpperCase())
I apologies for the poorly worded question, i dont know of any better way to explain what Im trying to achieve.
Im trying to determine the thread based on the device type. I could go in and do an
if (Constants.DEVICE.equals("TORO"){
String thread = Constants.TORO;
}
But I plan on adding a lot more device options in the future and would like to make it as easy as adding a string to the Constants.java rather than having to add another if clause.
I would suggest using an enum instead of just strings - then you can use:
String name = android.os.Build.DEVICE.toUpperCase();
// DeviceType is the new enum
DeviceType type = Enum.valueOf(DeviceType.class, name);
You can put the value of the string in a field for the enum, and expose it via a property:
public enum DeviceType {
RWFORUM("http://rootzwiki.com/forum/"),
TORO("362-cdma-galaxy-nexus-developer-forum");
private final String forumUrl;
private DeviceType(String forumUrl) {
this.forumUrl = forumUrl;
}
public String getForumUrl() {
return forumUrl;
}
}
(I'm guessing at the meaning of the string value - not a great guess, but hopefully it gives the right idea so you can make your actual code more meaningful.)
EDIT: Or to use a map:
Map<String, String> deviceToForumMap = new HashMap<String, String>();
deviceToForumMap.put("RWFORUM", "http://rootzwiki.com/forum/");
deviceToForumMap.put("TORO", "362-cdma-galaxy-nexus-developer-forum");
...
String forum = deviceToForumMap.get(android.os.Build.DEVICE.toUpperCase());
You can use reflection:
Constants.DEVICE = android.os.Build.DEVICE.toUpperCase();
String thread = (String) Constants.class.getField(Constants.DEVICE).get(null);
Not sure I've understood the question properly, but I feel that it's a right place to use a Map. The outcome will be something like this:
HashMap<String, String> map;
map.put(TORO, DEVICE);
Constants.DEVICE = android.os.Build.DEVICE.toUpperCase();
String thread = map.get(Constants.DEVICE);
Sorry for a possible misunderstanding or your question, but I hope you've got the idea.
P.S. You can find more info about Maps in the Java documentation: Map, HashMap.

Select object dynamically

Here's the situation :
I have 3 objects all named **List and I have a method with a String parameter;
gameList = new StringBuffer();
appsList = new StringBuffer();
movieList = new StringBuffer();
public void fetchData(String category) {
URL url = null;
BufferedReader input;
gameList.delete(0, gameList.length());
Is there a way to do something like the following :
public void fetchData(String category) {
URL url = null;
BufferedReader input;
"category"List.delete(0, gameList.length());
, so I can choose which of the lists to be used based on the String parameter?
I suggest you create a HashMap<String, StringBuffer> and use that:
map = new HashMap<String, StringBuffer>();
map.put("game", new StringBuffer());
map.put("apps", new StringBuffer());
map.put("movie", new StringBuffer());
...
public void fetchData(String category) {
StringBuffer buffer = map.get(category);
if (buffer == null) {
// No such category. Throw an exception?
} else {
// Do whatever you need to
}
}
If the lists are fields of your object - yes, using reflection:
Field field = getClass().getDeclaredField(category + "List");
List result = field.get();
But generally you should avoid reflection. And if your objects are fixed - i.e. they don't change, simply use an if-clause.
The logically simplest way taking your question as given would just be:
StringBuffer which;
if (category.equals("game"))
which=gameList;
else if (category.equals("apps"))
which=appList;
else if (category.equals("movie"))
which=movieList;
else
... some kind of error handling ...
which.delete();
As Jon Skeet noted, if the list is big or dynamic you probably want to use a map rather than an if/else/if.
That said, I'd encourage you to use integer constant or an enum rather than a String. Like:
enum ListType {GAME, APP, MOVIE};
void deleteList(ListType category)
{
if (category==GAME)
... etc ...
In this simple example, if this is all you'd ever do with it, it wouldn't matter much. But I'm working on a system now that uses String tokens for this sort of thing all over the place, and it creates a lot of problems.
Suppose you call the function and by mistake you pass in "app" instead of "apps", or "Game" instead of "game". Or maybe you're thinking you added handling for "song" yesterday but in fact you went to lunch instead. This will successfully compile, and you won't have any clue that there's a problem until run-time. If the program does not throw an error on an invalid value but instead takes some default action, you could have a bug that's difficult to track down. But with an enum, if you mis-spell the name or try to use one that isn't defined, the compiler will immediately alert you to the error.
Suppose that some functions take special action for some of these options but not others. Like you find yourself writing
if (category.equals("app"))
getSpaceRequirements();
and that sort of thing. Then someone reading the program sees a reference to "app" here, a reference to "game" 20 lines later, etc. It could be difficult to determine what all the possible values are. Any given function might not explicitly reference them all. But with an enum, they're all neatly in one place.
You could use a switch statement
StringBuffer buffer = null;
switch (category) {
case "game": buffer = gameList;
case "apps": buffer = appsList;
case "movie": buffer = movieList;
default: return;
}

Categories