Ideas on how to make user-defined variables within a Java program? - java

I am new in Stack Exchange, and I have been looking around for quite a while, with no answer. In my free time I am creating a matlab/like program in Java, I have noticed that I need to create a way of allowing the user to create its own variables from within the program. An example would be a = 5 and b = 3, and so when a + b = 8.
My first idea was to create a folder, where files can be saved as variables and then searched when the user calls for a particular variable. Any kind of feedback would be greatly appreciated. Thank you!

Simply you could do this using Map
Map<String, Integer> nameToValueMap
Ask user about name and put its value into map
Ask user to add two variables (lets say A, B) , fetch the associated values from map and manipulate it

You can create a Map
Map<String, Integer> variables = new HashMap<String, Integer>();
//add a variable
variables.put("a", 5);
variables.put("b", 3)'
//get value of variable
int a = variables.get("a");
int b = variables.get("b");
int output = a + b;

I suggest the use of Properties file. You can find more info and some examples here
They are really simple to read and write, and allow you to customize value of variables changing files. They have the advantage that you can keep all variable in a single file, simplifying your deployment environment.

Use a java.util.Map<String, Object> to store them

It seems to me that you are trying to implement a scripting language in Java. You could use one of the languages already available (e.g.: JRuby or Javascript), or create your application in Groovy, instead.
See also:
Scripting for the Java platform
Java Scripting Programmer's Guide

You are better off using a Map<String,Variable>.

Related

Dynamic Named SQL Fields

So i've got a bot that serves as a roleplaying mamager handeling combat, skill points and the like, i'm trying to make my code a bit more general so i can have less pages since they all do the same thing they just have different initilizers but i ran into a snag i need to check if the user has a minimum in a particular stat Strength, perceptions, agility, etc
so i call
mainSPECIAL = rows[0].Strength;
Here's the rub, weathers it strength, percpetion, intelligence, luck, whatever i'm always going to be checking Rows[0].that attribute ie Rows[0].Luck for luck perks, and i already set earlier in my initilizers
var PERKSPECIALName = "Strength";
But i can't call
mainSPECIAL = rows[0].PERKSPECIALName but there should be a way to do that right? so that when it sees "rows[0].PERKSPECIALName" it looks up "PERKSPECIALName" and then fetches the value of rows[0].Strength
For this you need to use reflection:
Field f1 = rows[0].getClass().getField(PERKSPECIALName);
Integer attribute = (Integer) f1.get(rows[0]);
Where "Integer" is the type of the element your pulling from the object (the type of strength)
The field must be declared as public! I think there is a way to obtain them when they are not public but it requires more code.
Seems like you have a set of integers that you need to identify with a constant identifier. You might find an EnumMap useful. Have a look at How to use enumMap in java.
Or if you want to only use a string to identify which perk you want to reference, just use a Map.
Java doesn't have reference-to-member like some other languages, so if you don't want to change your data structure, you are looking at using lambda functions or heavier language features to increase re-use, which seems like overkill for what you're trying to do.

Get variable name of object from an ArrayList

I am creating an ArrayList of JTextFields using the following code.
ArrayList<JTextField> cmp = new ArrayList<>();
cmp.add(txtAmount);
cmp.add(txtBillTo);
cmp.add(txtBranch);
After passing this ArrayList into a method, I need to print the "variable name" of the textfield. I can use the SetName and GetName to print some names. But I need the output as txtAmount, txtBillTo, txtBranch.
Is there anyway to find the variable name of textfield?
No, you can't do this. The information you are asking for is just not recorded. The only way to do it would be to store it yourself:
Map<String, JTextField> cmp = new HashMap<>();
cmp.put("txtAmount",txtAmount);
cmp.put("txtBillTo", txtBillTo);
cmp.put("txtBranch", txtBranch);
If you need to keep things in the same order you put them into the collection then use a LinkedHashMap instead of a HashMap as the HashMap may change the order.
What you are looking for would require reflection of method code, something supported by languages such as Scala via macros/compile time reflection. However Java itself does not support runtime or compile time reflection of method code, only runtime reflection of classes/fields/functions, although some people have pulled together their own Java parsers to grab the information from source files and others have pulled the information from the Class files debug information. Neither of which has an officially supported API.
Your best bet is to place the name that you want along with the field, which is obviously duplication and thus could diverge by accident but your options are limited.

How to create a variable name at runtime?

I am not able to create the name of the object at runtime. My statement is:
Map<String,String> objectName+""+lineNumber = new HashMap<String,String>();
It's giving me compiletime error. I want to create the HashMap object at runtime depending upon the line number.
Java is not a interpreted but rather a compiled language. So the compiler does not knows how to handle this. Such a thing might make sense in a scripting language.
If you need a custom Name for a "variable" maybe a construct like the following might make sense:
Map<String,Map<String,String>> varMap = new HashMap<String,Map<String,String>>();
varMap.put(objectName+" "+lineNumber, new HashMap<String, String>());
You can't do this directly in Java (without major tricks)
What you can (and probably should) do:
Put your Map in another map which has the 'variable' name as a key.
If you really want to do that you have to do code generation. For this again you have multiple options:
Generate Java Source Code and compile it
Generate Java Byte Code on the fly. You might wanna look at this list: http://java-source.net/open-source/bytecode-libraries for libraries available.
Having a dynamic object name is of No Use.
At first, it's not possible to give reference a dynamic name. The bigger question is Why do you want to do it?
If, just for learning and doing experiments, I'll suggest you should follow proper exercises.
But, if you are trying to achieve some project requirement, Pls. explain the requirement. There will be some other way to achieve that.

Java: How should I store thing per-user in memory

I need to store values specific to a username into memory, I was thinking about something like dynamically naming vars, so that I could do something like
["bubby4j_falling"] = true;
and index it by
["bubby4j_falling"]
But, this is just a example, I know that won't work, I just want a way to quickly and simply get and store things dynamically.
You want to use a Map with string keys, for example a HashMap<String, something>.
Your example would look like this:
Map<String, Boolean> map = new HashMap<String, Boolean>();
map.put("bubby4j_falling", true);
if(map.get("bubby4j_falling")) {
...
}
Actually, in your case a Set<String> would be more useful:
Set<String> fallingUsers = new HashSet<String>();
fallingUsers.add("bubby4j");
if(fallingUsers.contains("bubby4j")) { ... }
But uf you already have User objects (and you should), you should better use a Set<User>, or even let this falling simply be a property of the user object. Then you could have a Map<String, User> to get the user objects by name.
#PaĆ­lo Ebermann's answer is spot on.
I just want to point out that the Java language has nothing that resembles a dynamic variable. All Java variable names and their types are declared in the Java source code. Not even reflection will allow you to create new variables on the fly in an existing class.
Java is designed as a static programming language, and it works best if you use it that way.
(In theory, if you mess around with source code or byte code generation technologies, you can dynamically create a new class with new variables. However, this involves a HUGE amount of work, and not something that a sensible programmer contemplate doing to solve a simple problem. Besides, I doubt that this approach would actually help in your particular case.)

Java, How to save values in a permanent file and load from that

I want to be able to pull values from a file that is saved, and that I can edit, and add to from in the program or just outside of it.
Just a basic list of values.
this = that
this2 = that2
this3 = that3
And then query this, and get that out of it.
What is the best way to do this?
You can use either Properties, if you use your own files; or Preferences if you want the location to be default.
A comparison between the two APIs is found here.
As to the kind of values, theoretically anything could be stored (by serializing to String), but the APIs are best suited to fundamental types like String, Integer and the like.
In your case I'd recommend Properties as these use a text file (the name provided by you), which you can edit with any tool you want. Preferences might be stored in the Windows registry (as far as I know) which may not be suitable for you.
If you want to use Preferences, here is some exampe code:
In your class MyClass, declare..
private Preferences preferences = Preferences.userNodeForPackage(MyClass.class);
private final String item1 = "item1"; // These are the keys (names) to identify your
private final String item2 = "item2"; // items in storage.
This code will retrieve a value..
preferences.getInt(item1, 0); // the 0 is a default that will be returned
// if a stored value can't be retrieved.
This code will store a value..
preferences.putInt(item1, 4); // store an int in item1
As mentioned by #extraneon, on Windows, these will be stored in the registry. Other systems may use a file stored in the user's home directory. I only show storing and retrieving ints but you can store many other basic types too.
You should take a look at the documentation for Preferences.userNodeForPackage() to fully understand what it does. This will associate the stored items with your application/class.

Categories

Resources