【发布时间】:2020-11-09 06:14:33
【问题描述】:
我正在尝试用 Java 制作一个 gematria 计算器,并尝试获得与 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."
但是,如果输入 AB 或 AA 作为输入,输出将是:
"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 程序中输入aa 或ab,我会得到:
"The gematria of aa is 2."
"The gematria of ab is 3."
因此,将用户输入转换为大写会很好,但这不是我在这里要问的主要内容。
我的主要问题是:如何在 java 中获得与在 python 中相同的最终结果?
【问题讨论】:
-
请查看问题,示例和问题很清楚,但问题并不完全代表您遇到的问题。我会增加得到回复的机会。