0

Suppose I have a file with content:

I want to declare a variable called science.
I want to declare a variable called commerce.

Now I want to declare variables based on last word of each line in the above file. Eg:-

public static String SCIENCE;
public static String COMMERCE;

How can I achieve this? I think this question tries to do the same thing with bash.

How could it be done in java?

Community
  • 1
  • 1
ashish mishra
  • 1,401
  • 2
  • 10
  • 13
  • 1
    It's not at all clear what you're trying to achieve. Is your program meant to output source code, or do something else? Also, what would the type of these variables be? (The source code you've described isn't valid at the moment.) – Jon Skeet Jun 17 '16 at 05:52
  • variables are supposed to be string type ... i forgot to mention that ... sry for inconvinience. – ashish mishra Jun 17 '16 at 06:07
  • 1
    Sounds like a job for a `Map`. – user207421 Jun 17 '16 at 06:15
  • can we do this : String aa = "bb"; String bb = "cc" i.e. aa = cc Is there a process to do so? – ashish mishra Jun 20 '16 at 04:54

3 Answers3

2

Generally is not necessary to give a name to a variable but have the opportunity to retrieve that variable with a name.

Consider to store your variable in Map<String, Object> where the key is the name of your variable. A Map is:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

A code similar to the following can help:

Map<String, Object> map = new HashMap<String, Object>();

...
// To store an object with a key myName
map.put("myName", obj);

...
// To retrieve an object with a key myName
Object obj = map.get("myName");
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
2

It is impossible to declare the variable names in running time. You can try another way:

Map<String, Object> maps = new HashMap<>();
maps.put(the last word of each line, the value);

Get the value by the last word of each line:

maps.get(the last word of each line);
star
  • 321
  • 2
  • 9
0

Perhaps you could create some sort of abstract class or interface that represents the variable. Then you could have it initialized by converting a string into code using something like this Convert String to Code.

Community
  • 1
  • 1