I need to create new variables Strings such that
String person1 = "female";
String person2 = "female";
........
........
String person60 = "male";
........
String person100 = "male";
This is what I tried
for (int i = 1; i <101; i++) {
if (i<60) {
String person+i = "female";
}
else {
String person+i = "male";
}
}
Can anybody help me correct this code?
解决方案
A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value
Map details = new HashMap<>();
for (int i = 1; i <101; i++) {
if (i<60) {
details.put("person" + i, "female");
}
else {
details.put("person" + i, "male");
}
}
Java设置动态变量的解决方案
博客围绕Java设置动态变量展开,作者尝试创建多个String类型变量,如person1到person100并赋予不同值,但代码有误。解决方案是使用Map,通过循环将变量名作为键,对应的值作为值存入Map中,实现动态变量设置。
5万+

被折叠的 条评论
为什么被折叠?



