java - 如何根据用户输入在哈希表中添加某些值?

标签 java python hashtable

我正在尝试制作一个 gematria Java 中的计算器并尝试获得与使用 python 得到的相同结果。我如何在java中得到这样的结果,它可以打印用户输入的值的总和,并得到与python中相同的最终结果?请注意,我是java初学者,所以请原谅我对这个问题的任何无知。

我设法用 python 做了一个,并想用 java 做一些概念上类似的事情。在 python 中,我有一本包含所有英文字母及其数值的字典。

Python代码

    Letter_values = {" ":0, 
    `"A": 1,`   
    "B": 2,
    # goes through rest of alphabet.}
    New_total = []  
    def get_gematria():  
          word = input("What do you want the gematria of?")
          upper_word = [x.upper() for x in word]
          for i in upper_word:
          New_total.append(Gematria[i])
          print(F"The gematria of {word} is {sum(New_total)}.")
          New_total.clear
          get_gematria() 
    get_gematria() 

根据我对 Java 的理解,我会做一个哈希表,并且我知道如何将其写出来。

Java代码

    package com.company;
    import java.util.*;
    public class Main {

           public static void main(String[] args)  {
             Hashtable<String, Integer> Letter_Values = new Hashtable<>();
             Letter_Values.put("A", 1);
             Letter_Values.put("B", 2);
            // Goes through rest of alphabet
             System.out.println("What do you want the gematria of?")
             Scanner i = new Scanner(System.in);
             String Gematria = i.next();
             System.out.println("The gematria of " + Gematria + " is " 
               + Letter_Values.get(Gematria))

因此,在 Java 程序中,如果输入为 "A" (不带引号)作为输出,我将得到:

"The gematria of A is 1."

对于输入,我输入“B”(不带引号)作为输出,我将得到:

"The gematria of B is 2."

但是,如果输入 ABAA 作为输入,输出将为:

"The gematria of AB is null."

我还尝试在此处放置一个 for 循环:

for (int j = 0; j <Gematria.length(); j++) {
    System.out.println("The gematria of " + Gematria + " is " 
      + Gematria_Values.get(Gematria));

因此,如果我将 A 作为输入,我会得到与之前相同的结果:

"The gematria of A is 1."

但是,如果我输入 AA 或我得到的任何字母组合。

"The gematria of AA is null."
"The gematria of AA is null."

我明白了

"The gematria of x is null."

根据字母的数量,我输入。所以如果我输入AAAA。输出:

"The gematria of AAAA is null." 4 Times

我认为它清楚地表明了我通过 java 代码得到了什么。

在 python 程序中,如果我输入 aaab 我得到:

"The gematria of aa is 2."

"The gematria of ab is 3."

因此,将用户输入转换为大写会很好,但这不是我在这里问的主要问题。

我的主要问题是:如何在 java 中获得与 python 中相同的最终结果?

最佳答案

更新你的 for 循环

for (int j = 0; j <Gematria.length(); j++) {
    System.out.println("The gematria of " + Gematria + " is " + Gematria_Values.get(Gematria));

int sum = 0;
for (int j = 0; j < Gematria.length(); j++) {
    sum+= Letter_Values.get(String.valueOf(Gematria.charAt(j)));
}
System.out.println(sum);

关于java - 如何根据用户输入在哈希表中添加某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62987856/

相关文章:

java - 使用 UIL 显示图像的 Pinterest 风格

java - java eclipse代码完成中的这些数字 `10k` , `6k` , `1k` , `210` 是什么意思?

java - 了解 Spring security 中的身份验证提供程序

python - 自定义字体的 Kivy 标签标记

python - 从Python中的列表列表中提取槽

c - 为什么我有时只会遇到段错误?

algorithm - 寻找哈希算法的伪代码(开放、链接和多重)

java - 哈希表中的链表

java - GridBagLayout 组件无法正确显示

python - 编译 new_op 教程时出错(Tensorflow)