【问题标题】:Logic error, assigning value to different type逻辑错误,给不同类型赋值
【发布时间】:2015-04-14 03:43:52
【问题描述】:

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

e.g.

F = 56
H = -25

【问题讨论】:

  • 请更具体。此外,char 不能为负数。
  • 你的问题不清楚。

标签: java methods char integer


【解决方案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 值类型

您可以通过 main 方法或其他方法以与用户交互的方式使用它。示例

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)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2010-12-22
    • 2018-05-22
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多