How can I set the values of variables with a loop? For example:
String cur[]= {"A","B"};
String strA,strB;
for(int i =0;i < cur.length;i++) {
str+i开发者_C百科 = "Blah";
}
what should go in the "str+i" part so it sets strA and strB to "Blah"?
Thanks
You don't do that. Instead, you create a collection of some type. For example, you might use a map:
String[] cur = { "A", "B" };
Map<String, String> map = new HashMap<String, String>;
for (String name : cur)
map.put(name, "Blah");
}
Unless you use reflection (which won't help for local variables), you can't "compute" the variable name to use... and you shouldn't be using reflection for something like this.
That's assuming you want to access values by a string name. If you can use a contiguous range of integers (starting from 0), then an array or a List<T>
might be more appropriate. It depends on what you're trying to do.
There is no simple way of doing exactly what you want. However, there is a simple alternative: instead of individually naming your Strings, just use a single array.
String[] cur = new String[2];
for (int i = 0; i < cur.length; ++i) {
cur[i] = "Blah";
}
If you must access these Strings by name rather than index, look into creating a Map<String, String>
.
You can't. You probably shouldn't.
To strictly what you want you should use probably the java.lang.reflect classes. It allows you do some sort of dynamic member access you see possible in languages such us javascript and/or ruby. But it seems overkill in this case.
Another other more useful solution is what mr. Jon Skeet proposed. Depending on your actual needs it might just work.
You can do something kind of like that although I'm not sure why you'd want to:
import java.lang.reflect.Field;
public class Test {
static public String strA, strB;
public static void main(String args[]) throws Exception {
String cur[]= {"A","B"};
for(int i =0;i < cur.length;i++) {
Field field = Test.class.getField("str" + cur[i]);
field.set(null, "Blah");
}
System.out.println(strA);
System.out.println(strB);
}
}
精彩评论