0

There's probably a better way to do this, but i basically want a user input that can be set an indefinite amount of times in a new variable each time. I was trying to figure out how to set a variable with a variable in its name.

Coming from DOS Batch I'd do something like:

set /A num=0

set /A coins%num%=%num% & set /A num=(%num%+1)

This sets a new variable each time under the variable "coins1,coins2,coins3" depending on the value of "num"

tshepang
  • 12,111
  • 21
  • 91
  • 136
FFF
  • 741
  • 1
  • 8
  • 19
  • 3
    If I had a quarter for every time this question were asked... :) – Hovercraft Full Of Eels Oct 11 '12 at 01:46
  • You can't have dynamically referenced variables like you're trying; the closest thing you can get is a `Map`. – Louis Wasserman Oct 11 '12 at 01:46
  • 1
    sorry i looked around on the forum, couldn't find it :\ – FFF Oct 11 '12 at 01:53
  • I sometimes prefer to use Google to search SO using the `site:stackoverflow.com` command, something like: [Google StackOverflow for Dynamic Variable Names](https://www.google.com/#hl=en&sclient=psy-ab&q=site:stackoverflow.com+java+dynamic+variable+names) – Hovercraft Full Of Eels Oct 11 '12 at 02:02
  • This is a possible duplicate of [Dynamic Variable Names in Java](http://stackoverflow.com/questions/6729605/dynamic-variable-names-in-java). Voting to close as we already have plenty of this question here, more than enough, I think. – Hovercraft Full Of Eels Oct 11 '12 at 02:03

2 Answers2

1

There are a number of basic structures that will do what you want, the most common being lists and arrays...

I'd start by having a look at Arrays for an introduction.

When that makes sense, I'd take a look at Collections

The main difference (in this context), is that an array tends to be of fixed length where as a list can be of variable length

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You cannot do what you want directly.

The closest you can come is to use a collection to store the variable names (keys) and values (values)

I would use a Map<String, Object> for this purpose.

So if user specifies a variable name "var1" (as variableName) and a value "some value" as (value), you can do

// do this once
Map<String, Object> vars = new HashMap<String, Object>();
// every time you get a new "variable" and value do 
vars.put(variableName, value);

If you ever need to get all the "variables" entered, you can use the keySet method to get a collection of the keys. Docs Here.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236