GrGom
GrGom

Reputation: 68

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

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!

Upvotes: 1

Views: 2429

Answers (6)

ratchet freak
ratchet freak

Reputation: 48216

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

Upvotes: 0

theglauber
theglauber

Reputation: 29625

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

Upvotes: 0

Nitin Chhajer
Nitin Chhajer

Reputation: 2339

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;

Upvotes: 2

Johm Don
Johm Don

Reputation: 629

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

Upvotes: 0

Andrea Parodi
Andrea Parodi

Reputation: 5614

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.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240928

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

Upvotes: 5

Related Questions