Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top