Java中如何将Scanner获取的用户输入作为变量名使用
Java 能否使用运行时输入的字符串作为变量名
你想要的直接用Scanner获取的字符串作为变量名定义变量的写法,在Java中无法实现。
原因说明
Java是静态编译型语言,所有变量的名称、类型都需要在编译阶段就确定完成,编译后变量名会被转换为内存地址引用,不会保留到程序运行阶段。你在运行时通过用户输入拿到的字符串属于动态生成的内容,不可能回溯修改编译阶段就已经固定的变量定义规则。
等价替代方案
你可以使用HashMap实现完全一致的使用效果,把用户输入的自定义名称作为Map的键,你要存储的变量值作为值即可,示例代码如下:
import java.util.HashMap; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); // 定义存储自定义变量的Map,键为自定义变量名,值为对应的int数据 HashMap<String, Integer> customVariables = new HashMap<>(); System.out.println("What is this variable's name??"); String customName = input.next(); // 存入自定义变量,等效于你想要的 int 自定义名称 = 0 customVariables.put(customName, 0); // 后续读取变量值 System.out.println(customName + "的值为:" + customVariables.get(customName)); // 修改变量值 customVariables.put(customName, 200); System.out.println("修改后" + customName + "的值为:" + customVariables.get(customName)); } }
如果需要存储多种不同类型的变量,可以把HashMap的泛型值改为Object,使用时做对应类型转换即可。
内容的提问来源于stack exchange,提问作者Åke
相关产品推荐
相关产品推荐

