java - 如何在变量名中使用方法?

标签 java variables for-loop methods

我必须创建一些变量,例如:“n23、n4、n18...”。
因此,它们由两部分组成:字母“n”和一个我想从生成随机数的方法(rand())中获得的数字。

类似这样的事情:

for(int i = 0; i < 6; i++) {
    int n*here_must_be_random_number_got_from_my_method*;
}

是否可以做类似的事情?

最佳答案

Java 不是脚本语言。

所有标识符,即所有包名、类型名、方法名、字段名和变量,都必须在编译时指定。因此,无法根据运行时计算的值来连接变量名称。

但是!

你甚至不需要。只需使用java.util.Map。而不是做

int n*here_must_be_random_number_got_from_my_method* = *whatever_it_is_you_want_to_put_here*;

你可以这样做

Map<Integer, Integer> myMap = new HashMap<>();

一次,然后将值放入 map 中,如下所示:

myMap.put(*here_must_be_random_number_got_from_my_method*, *whatever_it_is_you_want_to_put_here*);

然后像这样取回它:

myMap.get(*here_must_be_random_number_got_from_my_method*);

关于java - 如何在变量名中使用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730824/

相关文章:

r - R中的for循环不绑定(bind)文件

java - 格式化字符串时%df代表什么?

java - 从对象数组数据java中删除重复项

c++ - Visual Studio /C++ : Find all variable accesses in code?

python - 未绑定(bind)的变量和名称

c - 在C语言中,数组的大小在运行时确定?

java - Micrometer @Timed 注解

Java多线程客户端/服务器-java.net.SocketException : Socket closed

bash - 为什么 `for i in {1..10}` 与 `for ((i=1; i<=10; i++))` 不同?

python - 在 python 中是否有更简单的方法来编写 6 个嵌套的 for 循环?