How to name an array with a variable in java? - java

I am trying to make a calendar in Java that will store events such as doctors appointment, etc. I plan on storing these events as String arrays, containing the name of the event, the location of the event, and the time of the event. In order to generate new events, however, the arrays need to have unique names which I want to be the date they occur on. To do this, I planned on making a method that would take a new name for the array as a variable and then use that variable as the name of the array (as below):
public static void addInformation(String eventLabel) {
String eventName = JOptionPane.showInputDialog(null,"What yould you like the event to be called?");
String eventLocation = JOptionPane.showInputDialog(null, "Where will this event take place?");
String eventTime = JOptionPane.showInputDialog(null, "What time will this event take place? Input as: \"hours:minutes\" using a 24 hour clock.");
String[] eventLabel = {eventName, eventLocation, eventTime};
events.add(newEvent);
}
When I try this, I get an error saying: eventLabel is already defined in addInformation(java.lang.String)
Is there any way to name an array with a variable using a parameter? Any help would be appreciated. Thanks in advance.
EDIT:
It seems you cannot have a variable variable name. Is there a way to create a unique array each time this method is called?

Use a HashMap. For each entry, set the key using the eventLabel parameter, and value as your array. This way, you will have a name for each of your "arrays" (which will be an entry in the HashMap, in this case).

Your method declaration has eventLabel as type String. You try to redefine it as String[]. Try String[] eventLabelArray.
Hot Licks is correct - you cannot do something like addInformation('Arr') and have eventLabel be named 'Arr' and call Arr[0]. Why do you need it to be variable?

What you are trying to do is like using a variable name to create a variable name, I am not sure if this can be done.
But Maps can be used to solve your problem.Maps will provide your exactly same functionality as you want
for example:
Map<String, Something> myMap = new HashMap<String, Something>();
String name = eventName + eventLocation + eventTime;
myMap.put(name, new something);

eventLabel is used as both a local variable in the method as well as a passed-in argument. Give the two different names and that should fix your problem.

You cannot use the same name as the variable passed (String eventLavel) to your function
public static void addInformation(String eventLabel){
String eventName = JOptionPane.showInputDialog(null,"What yould you like the event to be called?");
String eventLocation = JOptionPane.showInputDialog(null, "Where will this event take place?");
String eventTime = JOptionPane.showInputDialog(null, "What time will this event take place? Input as: \"hours:minutes\" using a 24 hour clock.");
String[] arr = {eventName, eventLocation, eventTime}; // some other name!
events.add(arr);
}

It's good you're thinking about things this way, but I think you're trying to solve a non-problem.
Is there a way to create a unique array each time this method is
called?
Yes, it happens for free - you don't have to do anything. Because the array is being created inside the method, a new one gets created every time. So as others have said, just use a different variable name (not eventLabel) and you're good to go.

Related

call existing class by name in String variable

Let's say I have a
public class things {
String name = new string;
int nr = new nr;
//constructor etc
}
Now let's assume there are already a bunch of instances initialized. let's call them thingA, thingB, thingC (I will need them to be more later...)
I'm having a JFrame where the User can Input a text and the input shall be one of the classes so he could type "thingB", "thingD", ... "thingN"
within an actionPerformed I now want to:
String s = jLabel_1.getText();
and then do sth like.
System.out.println("" + s.nr)
Obviously, that doesn't work since s is a string only containing the value entered in the text-label, so what I wanna do is tell Java that the object's name I'm trying to use is the one saved in 's'. I really tried to look it up but I couldn't find anything except a
Class.forName(String...) option which didn't really work either, respectively I didn't know how to use it.

How to make a reference to the Variable in java and not to the Type of it

I have a specific question, so I start with an example:
I have some values of type String saved in variables as follows:
String one = "someValue";
String two = "anotherValue";
String three = "the last one";
and so on. This is of course a simple example, in the fact it will be methods that returns String Type and I save it in Variables to use further in code;
I also have a List of Strings that contains some namespaces, that should be a name of xml-elements:
List<String> namespaces = new ArrayList<Sting>(Arrays.asList("example:org:one", "example:org:two", "example:org:three"); //and so on
It will be seems as
<example:org:one></example:org:one><example:org:two></example:org:two><example:org:three></example:org:three>
in xml - document. But of course they also have some values, which are saved in String Variables ('one', 'two', 'three' respect.) and I would like to make a reference on it in Java code, but explicitly, not implicitly. Say, use as value 'one' -> but not a String 'one', but a Variable, which name is ONE. GOT THE IDEA?:
for(String s : namespaces) {
String[] arrayOfNamespaces = s.split(":");
int lengthOfArrayOfNamespaces = arrayOfNamespaces.length;
xmlBuilder.with(s, arrayOfNamespaces[lengthOfArrayOfNamespaces - 1]);
}
Is it possible? Is there something in java, that make a reference to a variable with the particular name in code: I believe it would be as something like Casting to VAR or as Annotation (maybe somebody had made something like this) :
...
xmlBuilder.with(s, #Var arrayOfNamespaces[lengthOfArrayOfNamespaces - 1]);
Or Mapping is the only way to make it works?

java get value from JTextField and set it as BigInteger

I have two classes in a package: firstClass and secondClass.
I created a textfield in firstClass, let's assume it's txtStringNumber.
I created a method in firstClass to get txtStringNumber value, like this:
public String getStrNumber(){
String strNumber = txtStringNumber.getText();
return strNumber;
}
I must pass it to secondClass as String and put the strNumber as BigInteger value.
In second class I created a method to get value of txtStringNumber from firstClass, like tis:
public static String theNumbers(){
firstClass f = new firstClass();
return f.getStrNumber();
}
public static String strAllNumbers = theNumbers();
When I print strAllNumbers in secondClass, it prints the correct value. Then I add this:
public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);
In my mind, it should works. But in real, it doesn't. Error occurs.
So I check the error, there said:
throw new NumberFormatException("Zero length BigInteger");
I guess BigInteger accept strAllNumbers as empty.
But just like I already said, when I print strAllNumbers directly without set it to BigInteger, it returns the correct value.
What's wrong here and how can I fix this?
You're creating a firstClass object, f, and getting a String from its textfield before anybody ever has a chance to enter text in it. So no surprise that it's empty.
Solution: Don't do this! Only get the text after something that makes sense has been entered.
I'm guessing that you have two firstClass objects, one displayed, and a second one created in this method, and are guilty of magical thinking that changes to the displayed object will be reflected in the newly created one, but that's not how programming works. Instead pass a valid reference of the displayed object to the other object that needs it.
You're creating a new instance of firstClass in the theNumbers method (firstClass f = new firstClass();), it's very unlikely the the value of the text field has been set to anything useful (especially by the user)
You either need to supply a means of firstClass to pass the value from the text field to secondClass, probably via a setter of some kind (this is classic producer-consumer pattern) or set up a mechanism for firstClass to notify secondClass when the value changes and then have secondClass retrieve that value (this is a class observer pattern).
In any case, you should not be creating a new instance of these classes, you need to create them and then pass these instance to which ever one is going to act as the controller...

How do I create a variable within another variable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic Variable Names in Java:
Let's say I have a string, as below.
String s = "Hello";
Now, I want to create a string, but the string's variable will be called "Hello". In order to make the string's name "Hello", I must access string s to get the name "Hello", so I can use it as a variable name. Below is what I want to see.
String Hello = "I want to do this, But from Accessing String s So I KNOW that String s = Hello";
Thank you for the effort, and please try to explain to me because I am a Java beginner. :D
What you are attempting to do is add a layer of indirection. You cannot access variables dynamically in a static language such as Java/C/C++/Pascal/etc
What you can do is emulate the dyamic context that dynamic languages use by, eg creating a Map to hold the variable names and values in this case you would have
Map<String,String> stringVars = new HashMap<String,String>();
// set a "variable"
stringVars.put("Hello", "value");
// get a "variable"
System.out.println(stringVars.get("Hello"));
Using Reflection (not recommended):
public class MainClass
{
public String Hello = "I want to do this, But from Accessing String s So I KNOW that String s = Hello";
public static void main(String[] args) throws Exception
{
MainClass m = new MainClass();
String s = "Hello";
String result = (String) MainClass.class.getField(s).get(m);
System.out.println(result);
}
}
OUTPUT:
I want to do this, But from Accessing String s So I KNOW that String s = Hello
Instead, use a map as others illustrated.
It is not possible in java.
The only thing you can do is to use A map interface' implementation, for example a HashMap. Using a put method you can 'assign' a value to a given 'name'. The name would be a key and has to be unique within a map, just like variable has a unique name within it's scope.
To retrieve the value, call get method passing appropriate key (ex. string 'Hello') as an argument.
In Java you cannot obtain the variable(reference) name which is pointing to an object since the object has no knowledge of the reference to it and there can be more than one variable refering to the same object.
On the other hand you could do somtething like this; but I do not know how would help:
String s = "Hello";
Reference<String> hello = new SoftReference<String>(s);
String myStringAccessedWithHello = hello.get();
Could you use a Map which takes a string (such as "Hello") and maps it to another String (such as "I want to do this, But from Accessing String s So I KNOW that String s = Hello"). Something like the following:
Map<String, String> stringMap = new HashMap<String, String>();
stringMap.put("Hello", "I want to do this, But from Accessing String s So I KNOW that String s = Hello");
Then you can find all of the key values in the map (such as "Hello") by calling:
Set<String> stringKeys = stringMap.keySet();
and you can lookup the long string belonging to the key "Hello" like this:
String longValue = stringMap.get("Hello");
This is how I would use a simple String value to find an unwieldy String value. Bear in mind you could also use a Map which maps String values to any other type of object.

Can I print out the name of the variable?

I have created a no. of constant variables, more than 1000, those constants are unique integer.
public static final FOO 335343
public static final BAR 234234
public static final BEZ 122424
....
....
....
Is there a way to print out the FOO, BAR and BEZ, the variable of the names in Java?
I am not familiar with java reflection. I don't know if that helps.
if ( FOO == 335343)
---> output "FOO"
if ( BAR == 234234 )
---> ouptut "BAR"
....
Actually asking this question behind is that I want to write log into the file
say
System.out.println("This time the output is " + FOO);
and the actual output is
This time the output is 335323
I want to know which variable comes from 335323.
Is there any other way apart from putting those variable and its associate constant into hashMap?
Thanks
There are some 'special case' that u can have workaround for this (which is told by other), but the most important question is: why would you want to do this (printing out variable name)?
From my experience, 99.9% of similar questions (how to print variable name? how to get variable depends on user inputting variable name? etc) is in fact raised by beginner of programming and they simply have made incorrect assumptions and designs. The goal they are trying to achieve normally can be done by more appropriate design.
Edit
Honestly I still do not think what you are trying to do is the way to go, but at least I think the following is a workable answer:
It is more or less a combination of previous answer:
(Haven't try to compile but at least it give u an idea)
class Constants {
public static final int FOO = 123;
public static final int BAR = 456;
private static Map<Integer, String> constantNames = null;
public static String getConstantName(int constVal) {
if (constantNames == null) {
Map<Integer, String> cNames = new HashMap<Integer, String>()
for (Field field : MyClass.class.getDeclaredFields()){
if ((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) {
&& int.class == field.getType()){
// only record final static int fields
cNames.put((Integer)field.get(null), field.getName());
}
}
constNames = cNames;
}
return constantNames.get(constVal);
}
}
assuming you want to get a constant name, just do:
Constants.getConstantName(123); // return "FOO"
As I noted in my comment to the original post, I have a strong suspicion that the best solution for your current problem is to solve it in a completely different way. You seem to want to associate an int with a String, and one way to do this is to use a Map such as a HashMap. For e.g.,
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(335343, "FOO");
myMap.put(234234, "BAR");
myMap.put(122424, "BEZ");
int[] tests = {335343, 234234, 122424, 101010};
for (int i : tests) {
// note that null is returned if the key isn't in the map
System.out.printf("%d corresponds to %s%n", i, myMap.get(i));
}
}
}
Edit 1:
Per your recent comments and update to your original question, I take it that you have many numbers and their associated Strings involved in this program and that your need is to find the String associated with the number. If so, then you need to think re-design, that the numbers and their strings should not be hard-coded into your program but rather be part of the program's data, perhaps in a text file with one column being the numbers and the next column (separated by a space perhaps), the associated text. This way you could read in the data and use it easily in a HashMap, or data base, or really any way that you desire. This will give your project much greater flexibility and robustness.
You can use something like:
for (Field field : MyClass.class.getDeclaredFields()){
if (field.getType().toString().equals("int")){
int val = (Integer)field.get(MyClass.this);
switch (val){
case 335343:
case 234234:
System.out.println(field.getName());
}
}
}
Remember to change MyClass for your class name and that at least one instance should exist to get the value of the field. So, if you are planning on testing the code in a main method, you should change MyClass.this to something like new Myclass().
Another thing to remember is that the fields are attributes and not method variables (so it won't work if you are using this to access variables declared inside a method).
You can use enum.
If these numbers just need to be unique, you can say
public enum Yourname {
FOO, BAR, BEZ
}
and refer to the name as Yourname.FOO and the value as Yourname.FOO.ordinal(). You can use enums for if-blocks, switch-statements.
If you want to have the numbers you gave in the question, so if FOO needs to be 335343, you can create numbered enums. Have a look at is-it-possible-to-assign-numeric-value-to-an-enum-in-java and number-for-each-enum-item.
I would suggest that you print out the line number, not the variable name. That should give you enough to determine where the message is coming from. Here's more info on how to do that:
How can we print line numbers to the log in java
I had a similar problem with a long list of int variables that I had to print the name of each variable and its value (main goal was to create a text file that was going to be imported in an Excel file).
Unfortunately I'm quite new in Java programming, so the only solution that I found (probably wrong) is to use two different arrays: one String array for the String name and another Int array for the corresponding values.
For example:
int varName01, varName02, ....
String[] listNames = new String {"varName01", "varName02", .....
int[] listValues = new int {varName01, varName02, .....
for (int i=0; i<listValues.length;i++)
{
print String.format("%s %d", listNames[i], listValues[i]);
}
Probably this is not the correct way to do it, so any opinion from some Java expert would be more than welcome. Thanks!

Categories