You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:45:03