java如何设置动态变量,如何在Java中动态创建变量?

Java设置动态变量的解决方案
博客围绕Java设置动态变量展开,作者尝试创建多个String类型变量,如person1到person100并赋予不同值,但代码有误。解决方案是使用Map,通过循环将变量名作为键,对应的值作为值存入Map中,实现动态变量设置。

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");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值