【问题标题】:Is there a better way to store and retrieve the values of letters given by their position in the alphabet? [duplicate]有没有更好的方法来存储和检索字母在字母表中的位置给出的值? [复制]
【发布时间】:2020-08-27 03:36:29
【问题描述】:

我有一个任务要编写一个程序,该程序将整数的数字和单词中的字母相加(每个字母的值由它在字母表中的位置给出,例如 j = 10)。经过一段时间试图找出存储和检索每个字母的值的方法后,我决定使用 HashMap ......但我想知道是否有更好的方法来做到这一点(我确定有)......所以我想得到一些关于如何改进代码和学习一些新东西的建议......谢谢!

import java.util.HashMap;
import java.util.Scanner;

public class NLS {

    public static HashMap<Character, Integer> alphabet;
    static {
        alphabet = new HashMap<>();
        alphabet.put('a', 1);        alphabet.put('b', 2);         alphabet.put('c', 3);        alphabet.put('d', 4);
        alphabet.put('e', 5);        alphabet.put('f', 6);         alphabet.put('g', 7);        alphabet.put('h', 8);
        alphabet.put('i', 9);        alphabet.put('j', 10);        alphabet.put('k', 11);       alphabet.put('l', 12);
        alphabet.put('m', 13);       alphabet.put('n', 14);        alphabet.put('ñ', 15);       alphabet.put('o', 16);
        alphabet.put('p', 17);       alphabet.put('q', 18);        alphabet.put('r', 19);       alphabet.put('s', 20);
        alphabet.put('t', 21);       alphabet.put('u', 22);        alphabet.put('v', 23);       alphabet.put('w', 24);
        alphabet.put('x', 25);       alphabet.put('y', 26);        alphabet.put('z', 27);
    }

    public static void main(String[] args) {
        char keepGoing;
        do {
            int sum;
            Scanner scan = new Scanner(System.in);
            System.out.println("\n\n\n____________________________________________________________");
            System.out.println("\n\tEnter a number [integer] or a word/sentence [no spaces]:\n");
            String input = scan.nextLine();
            boolean numeric = numberOrWord(input);
            if (numeric) {
                sum = digitSum(Integer.parseInt(input));
                System.out.println("Result= " + sum);
            } else {
                char letter = calculateLetter(input);
                System.out.println("Result= " + letter);
            }
            System.out.println("<<PRESS s/S TO CONTINUE>>");
            keepGoing = scan.next().charAt(0);
        } while (keepGoing == 's'||keepGoing == 'S');
    }

    public static boolean numberOrWord (String str){
        try{
            Double.parseDouble(str);
            return true;
        }catch(NumberFormatException e){
            return false;
        }
    }

    public static int digitSum(int number){
        int sum = 0;
        while(number > 0){
            sum = sum + number % 10;
            number /= 10;
        }
        return sum;
    }

    public static char calculateLetter(String word){
      
        int sumPV = 0;
        for(char digit : word.toCharArray()){
            sumPV += alphabet.get(Character.toLowerCase(digit));
        }

       /* for(int i = 0, l = word.length(); i < l; i++){
            char c = word.toLowerCase().charAt(i);
            sumPV = sumPV + alphabet.get(c);
        }*/

        while(sumPV > 27){
            sumPV =digitSum(sumPV);
        }
        char letter = (char) 0;
        for(char key : alphabet.keySet()){
            if(alphabet.get(key).equals(sumPV)) {
                letter = key;
            }
        }

        return letter;
    }

}



【问题讨论】:

  • 您不需要像这样存储值。您可以轻松计算它们。对于字母,小写字母的值等于c - 'a' + 1c - 'A' + 1 用于大写字母。

标签: java algorithm hashmap


【解决方案1】:

每个字符只是到整数值的映射,您可以通过执行简单的操作来打印它们的整数值以查看 A -> 65

char d = 'D'; // D is just 68

这样做

 d - 65 Or d - 'A'

两个结果都是 3

您可以对 char 使用整数值表示并像这样进行整数运算

public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        char a = 'A';
        System.out.println(a - 'A' + 1); //Returns 1
        a = 'B';
        System.out.println(a - 'A' + 1); //Returns 2
    }
}

[更新] 对于您的具体情况,您只需在替换之前将 ñ 替换为 O

【讨论】:

    【解决方案2】:

    您可以使用 Character.getNumericValue()。 这将为您提供字母的 ASCII 码。 由于“a”的代码不是 1,因此您需要通过例如

    来补偿它
    int n = Caracter.getNumericValue(c) - Character.getNumericValue('a') + 1;
    

    请注意,这仅在您只有小写字符时才有效。

    更接近您的代码的另一种方法是简单地使用包含 'a' ... 'z' 的字符串并使用 indexOf(c)。

    String alphabet = "abcdefg...z";
    int n = alphabet.indexOf("a") + 1;
    

    +1 是必要的,因为索引从 0 开始。

    【讨论】:

    • getNumericValue 根本不是这样做的。这实际上会起作用,但不是出于给出的原因。它也适用于大写字母。
    • 为什么不呢?根据 javadoc docs.oracle.com/javase/7/docs/api/java/lang/… getNumericValue() 返回字符的 unicode 值。由于高达 255 的 unicode 值相当于 ASCII 编码,因此我的代码可以正常工作。
    • 您是否阅读了您链接到的 javadoc?它非常清楚地表明 getNumericValue 不会返回字符的 Unicode 值。 @Ridcully
    • @DawoodIbnKareem 你是对的!我只看了第一段,应该进一步阅读。字母未映射到 ASCII 码。我的示例有效,因为代码从 a 到 z 递增,但正如您所说的那样,更多的是运气。
    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2022-09-22
    • 1970-01-01
    相关资源
    最近更新 更多