逻辑错误,将值分配给不同类型

时间:2015-04-14 03:43:52

标签: java methods char integer

我需要一些帮助来回答我自己的问题,所以我需要为一个角色分配一个int值。我看了看api。我想不出我该做什么。我需要分配用户指定的字符和int值,他/她将分配任何整数和他们想要的char。起初我想输入强制转换,但我不能让我的类型转换正常工作。有任何想法吗?



e.g.

F = 56
H = -25




1 个答案:

答案 0 :(得分:1)

已经有与字符关联的预定义值,这与编码有关。例如,A的值是65,B 66,......除了使用非常低级别的编程技术之外,您无法对其进行任意重新编程。现在,如果要将int值与字符关联,可以使用Map。

例如

Map<Character, Integer> charValues = new HashMap<Character, Integer>();
charValues.put('H',-25);
charValues.put('F', 56);

稍后在处理地图时,您可以使用例如

int valueForH = charValues.get('H');

Java的自动装箱和自动拆箱功能允许您从Character / Integer引用类型透明地转到char / int值类型

您可以通过主方法或其他方法与用户以交互方式使用它。实施例

public static void main(String[] args) {

    Map<Character, Integer> charValues = new HashMap<Character, Integer>();

    Scanner sc = new Scanner(System.in);
    while (true) {
        System.out.println("Enter a character and the corresponding value...");
        String data = sc.next();
        if ("exit".equals(data)) {
            break;
        }
        char car = data.charAt(0);

        int correspondingValue = sc.nextInt();
        charValues.put(car, correspondingValue);

    }

    // Here after exit you can use charValues.get(key) to get the int value    associated with the key (a char value)

}