有没有更好的方法来存储和检索字母的值,根据它们在字母表中的位置?

huangapple go评论118阅读模式
英文:

Is there a better way to store and retrieve the values of letters given by their position in the alphabet?

问题

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));
        }

        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;
    }

}
英文:

I've got an assignment to write a program that adds the digits of an integer and the letters in a word (the value of each letter is given by its position in the alphabet, e.g. j = 10). After a while of trying to figure out a way to store and retrieve the value of each letter I decided to use a HashMap... but I wonder if there are better ways to do it (I'm sure there are)... so I'd like to get some suggestions on how to improve the code and learn some new things... thanks!

import java.util.HashMap;
import java.util.Scanner;
public class NLS {
public static HashMap&lt;Character, Integer&gt; alphabet;
static {
alphabet = new HashMap&lt;&gt;();
alphabet.put(&#39;a&#39;, 1);        alphabet.put(&#39;b&#39;, 2);         alphabet.put(&#39;c&#39;, 3);        alphabet.put(&#39;d&#39;, 4);
alphabet.put(&#39;e&#39;, 5);        alphabet.put(&#39;f&#39;, 6);         alphabet.put(&#39;g&#39;, 7);        alphabet.put(&#39;h&#39;, 8);
alphabet.put(&#39;i&#39;, 9);        alphabet.put(&#39;j&#39;, 10);        alphabet.put(&#39;k&#39;, 11);       alphabet.put(&#39;l&#39;, 12);
alphabet.put(&#39;m&#39;, 13);       alphabet.put(&#39;n&#39;, 14);        alphabet.put(&#39;&#241;&#39;, 15);       alphabet.put(&#39;o&#39;, 16);
alphabet.put(&#39;p&#39;, 17);       alphabet.put(&#39;q&#39;, 18);        alphabet.put(&#39;r&#39;, 19);       alphabet.put(&#39;s&#39;, 20);
alphabet.put(&#39;t&#39;, 21);       alphabet.put(&#39;u&#39;, 22);        alphabet.put(&#39;v&#39;, 23);       alphabet.put(&#39;w&#39;, 24);
alphabet.put(&#39;x&#39;, 25);       alphabet.put(&#39;y&#39;, 26);        alphabet.put(&#39;z&#39;, 27);
}
public static void main(String[] args) {
char keepGoing;
do {
int sum;
Scanner scan = new Scanner(System.in);
System.out.println(&quot;\n\n\n____________________________________________________________&quot;);
System.out.println(&quot;\n\tEnter a number [integer] or a word/sentence [no spaces]:\n&quot;);
String input = scan.nextLine();
boolean numeric = numberOrWord(input);
if (numeric) {
sum = digitSum(Integer.parseInt(input));
System.out.println(&quot;Result= &quot; + sum);
} else {
char letter = calculateLetter(input);
System.out.println(&quot;Result= &quot; + letter);
}
System.out.println(&quot;&lt;&lt;PRESS s/S TO CONTINUE&gt;&gt;&quot;);
keepGoing = scan.next().charAt(0);
} while (keepGoing == &#39;s&#39;||keepGoing == &#39;S&#39;);
}
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 &gt; 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 &lt; l; i++){
char c = word.toLowerCase().charAt(i);
sumPV = sumPV + alphabet.get(c);
}*/
while(sumPV &gt; 27){
sumPV =digitSum(sumPV);
}
char letter = (char) 0;
for(char key : alphabet.keySet()){
if(alphabet.get(key).equals(sumPV)) {
letter = key;
}
}
return letter;
}
}

答案1

得分: 0

每个字符只是一个映射到整数值的关系,你可以打印它们的整数值,看到 A -> 65,通过进行简单的操作,比如

char d = &#39;D&#39;; // D 只是 68

所以执行

d - 65 或者 d - &#39;A&#39;

都会得到 3

你可以使用字符的整数值表示进行整数运算,像这样

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

[更新] 对于你的特定情况,你只需要在替换之前将 ñ 替换为 O。

英文:

Every char is just a mapping to integer value and you can print their intger values to see that A -> 65 by doing simple operations like

char d = &#39;D&#39;; // D is just 68

so doing

 d - 65 Or d - &#39;A&#39;

Both result in 3

You can use the integer value representations for char and do integer operations like so

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

[Update] For your specific case you just need to replace ñ with O before replacing

答案2

得分: -1

你可以使用Character.getNumericValue()。
这将为您提供字母的ASCII码。
由于该代码对于'a'不是1,您需要通过以下方式进行补偿:

int n = Caracter.getNumericValue(c) - Character.getNumericValue(&#39;a&#39;) + 1;

注意,这仅在您只有小写字符的情况下才有效。

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

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

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

英文:

You can use Character.getNumericValue().
This will give you the ASCII code for the letter.
As that code is not 1 for 'a' you need to compensate that by e.g.

int n = Caracter.getNumericValue(c) - Character.getNumericValue(&#39;a&#39;) + 1;

Note, that this will only work if you have only lower case characters.

A different approach, closer to your code, would be to simply use a string containing 'a' ... 'z' and use indexOf(c).

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

The +1 is necessary because index starts with 0.

huangapple
  • 本文由 发表于 2020年8月27日 11:36:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63608775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定