使用 hashMap 为 char 赋值

using hashMap to assign val to char

我正在尝试使用 HashMap 将整数值分配给大写字母。 我可以为一个字符分配一个值;但是,我需要将每个值存储到特定字符 [请记住,字母和整数值都是由用户指定的]。这是我需要帮助的地方。

我需要将用户定义的整数值存储到用户定义的字符中,对于每个字母,如果没有分配整数值,那么它会保留其在字母表中位置的整数值。我不知道如何循环并使用 HashMap 对象

执行此操作

目前我将 int 值存储在 char 中作为 >>> mapObj.put(ch,intValue);

并调用 >> int getValue = mapObj.get(ch);

但它只调用我想同时调用字母和值的值,如果可能的话。

我试过循环播放和循环播放,但我都无法使逻辑正确。

Map<Character, Integer> mapObj = new HashMap<Character, Integer>();
Scanner kbd = new Scanner(System.in);
String str = " ";
char ch = ' ';
int startIndex;
int strLength;
int value = 0;
String strValue = " ";
while(kbd.hasNext())
{
    str = kbd.nextLine();
    if(str.equals("QUIT"))
    {
        break;
    }
    else
    {
        ch = str.charAt(0);
        startIndex = str.lastIndexOf(" ")+1;
        StringLength = str.length();
        strValue = str.substring(startIndex,StringLength);
        value = Integer.parseInt(strValue);

        System.out.println(""+strValue);
        tempIndex.put(ch,value);
        int VarValue = tempIndex.get(ch);
        System.out.println(ch+" = "+VarValue);
    }
}

在不给你代码(给你的作业)的情况下,这里有两种不同的情况(如果我理解你的问题的话):

  1. char c 分配了一个整数 -> return 分配的整数
  2. 字符 c 没有 整数 - return c 的字母位置

这可以通过以下方式实现:

  1. 首先使用分配给整数 1-26 的字母 A-Z 填充映射 - 这将加强 "nth letter" 映射
  2. 让用户指定覆盖步骤 1 中的分配的自定义分配(再次调用 map.put() 覆盖)

现在你有一张地图,里面有你想要的东西。

如果您只想在地图中存储 26 个值,为什么不对可怜的旧微处理器有一点机械同情,而只使用数组呢?

例如HashMap实现...

package Whosebug;

import java.util.HashMap;
import java.util.Map;

public class MapVsArray1 {

    public static void main(String[] args) {
        String input = "The quick lazy fox forgets how to type the sentance so that each letter appears only once and something to do with jumping over something";

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

        for (int k = 0; k < input.length(); k++) {
            char key = Character.toUpperCase(input.charAt(k));

            if (key >= 'A' && key <= 'Z') {
                Integer currentCount = map.get(key);

                if (currentCount == null) {
                    currentCount = 0;
                }

                currentCount++;
                map.put(key, currentCount);
            }
        }

        // Output results (rely on HashMap's toString)...
        System.out.println(map);

    }
}

输出:

{D=2, E=14, F=2, G=4, A=7, C=4, L=3, M=3, N=8, O=12, H=8, I=5, J=1, K=1, U=2, T=14, W=2, V=1, Q=1, P=4, S=6, R=4, Y=3, X=1, Z=1}

而使用数组...

package Whosebug;


public class MapVsArray2 {

    public static void main(String[] args) {
        String input = "The quick lazy fox forgets how to type the sentance so that each letter appears only once and something to do with jumping over something";

        int[] counts = new int[26];

        for (int k = 0; k < input.length(); k++) {
            char key = Character.toUpperCase(input.charAt(k));

            if (key >= 'A' && key <= 'Z') {
                counts[key - 'A']++;
            }
        }

        // Output results...
        for (int i = 0; i < counts.length; i++) {
            char letter = (char) ('A' + i);
            System.out.print(letter + "=" + counts[i] + " ");
        }

    }
}

输出...

A=7 B=0 C=4 D=2 E=14 F=2 G=4 H=8 I=5 J=1 K=1 L=3 M=3 N=8 O=12 P=4 Q=1 R=4 S=6 T=14 U=2 V=1 W=2 X=1 Y=3 Z=1 

基本上,数组解决方案的计算成本较低。

看了你的问题十多遍还是不明白你在问什么。你说

I have tried for looping it and while looping it, neither of which I can get the logic correct.

我敢打赌,您是在询问如何遍历 Map 中的条目,对吗? (反正我看不出你在引用不相关的代码……)

如果是这样,我们通常会这样做:

Map<Foo, Bar> myMap = ....;

for (Map.Entry<Foo,Bar> entry : myMap.entrySet()) {
    System.out.println("key is a Foo, which is " + entry.getKey());
    System.out.println("value is a Bar which is " + entry.getValue());
}

首先创建一个 Map<Character, Integer> 并用 {A-Z}{[= 填充它15=]-26}

Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i + 'A' <= 'Z'; i++) {
    char key = (char) ('A' + i);
    int defaultValue = i + 1;
    map.put(key, defaultValue);
}

如果我们现在 运行 System.out.println(map); 我们会看到

{A=1, B=2, C=3, D=4, E=5, F=6, G=7, H=8, I=9, J=10, K=11, L=12, M=13, N=14, O=15, P=16, Q=17, R=18, S=19, T=20, U=21, V=22, W=23, X=24, Y=25, Z=26}

这意味着 map 现在 已初始化 。接下来,我将使用 hasNextLine()nextLine() 以及更通用的 Scanner 名称。如果您想使用由文件支持的 Scanner 怎么办?我会使用 String.split(String) 将输入分隔成标记。像,

Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
    String line = scan.nextLine();
    if ("quit".equalsIgnoreCase(line)) {
        break;
    }
    if (!line.isEmpty()) {
        String[] arr = line.toUpperCase().split("\s+");
        char ch = arr[0].charAt(0);
        int val = Integer.parseInt(arr[arr.length - 1]);
        if (ch >= 'A' && ch <= 'Z') {
            map.put(ch, val);
        }
    }
}
System.out.println(map); // <-- output after getting all of the input