stepping through numbered variable names
Hi,
This is probably a very easy question, I'm just going bonkers trying to guess it.
I'm writing a little program for myself to develop my skills & one thing I have in my program is a set of textfields (in swing) lets just say called Text1 to Text5.
When I hit my save button I want to set up a 'for' loop to step through 5 times & if there is text, to write the Text of the text box to an ArrayList.
for example I wrote
Code:
for (int x = 1; x<=5; x++){
if (Text(x) <"") {
myArrayList.add(Text(x).getText());
}
}
essentially it's the x's in brackets in lines 2 & 3 that I'm unsure of.
I dont want to statically hardcode Text1, Text2, etc, I want the code to do it for me.
I know it must be possible, I've tried no brackets, square Brackets & regular brackets all to no avail. - what do I need to do..?
Thanks in advance,
PJ
Re: stepping through numbered variable names
With that syntax, the compiler will think that you are trying to call a method named Text.
You must create all variable names when you type in the code. The compiler does not generate variable names.
You can use an array of TextFields to hold references to TestFields and then index into that array.
Re: stepping through numbered variable names
What you want to do is easy: you should create an array or collection of JTextFields if you desire to do something like this. (as Norm already mentioned).
The variable name is not nearly as important as you think since it almost doesn't even exist in the compiled code. What matters is the reference and an array or collection will allow you to access the references to the fields.
Re: stepping through numbered variable names
Quote:
Originally Posted by
Norm
With that syntax, the compiler will think that you are trying to call a method named Text.
You must create all variable names when you type in the code. The compiler does not generate variable names.
You can use an array of TextFields to hold references to TestFields and then index into that array.
You're exactly right.
I just thought there might be a way so that in iteration 1 it would add Text1 to the arrayList, in iteration 2 would add Text2 etc. seems that I need to dump it into an array first? (which would necessitate the same code as putting it into the ArrayList anyway!).
Oh well, it's good to try these things. Thanks for your swift responses. - Much appreciated.:(clap):
- PJ.