java—将数字转换为德语单词

cetgtptt  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(308)

所以我的任务是把数字转换成德语,我对“ein”和“eins”有问题。
每当我输入101101-->时,我得到的是“einhunderteinstausendinunderteins”,这是不正确的,它只是数字中最后一个需要以s-->“eins”结尾的ein,但不知怎么的,我也有einstausend中的eins?有什么办法解决这个问题吗?

public abstract class InGerman {

    public static void main(String[] args) {
        int number = Terminal.getInt("Enter a number between 1 - 999999:  --->  ");
        Terminal.put("number in german: " + inGerman(number));
    }

    public static final String[] unitsArray = {" ", "eins", "zwei", "drei", "vier", "fünf", "sechs", "sieben", "acht",
            "neun", "zehn", "elf", "zölf", "dreizehn", "vierzehn", "fünfzehn", "sechszehn", "siebzehn", "achtzehn",
            "neunzehn"};
    public static final String[] tensArray = {" ", "zehn", "zwanzig", "dreissig", "vierzig", "fünfzig", "sechszig",
            "siebzig", "achtzig", "neunzig"};

    static int einer = 0;

    private static String inGerman(int number) {
        // variable to hold string representation of number
        String words = "";

        while (number == 0 || number == 1) {
            if (number == 0)
                return "null";
            if (number == 1) {
                return words + "ein";
            }
        }
        // check if number is divisible by 1 million
        if ((number / 1000000) > 0) {
            words += inGerman(number / 1000000) + "million" + "";
            number %= 1000000;
        }
        // check if number is divisible by 1 thousand
        if ((number / 1000) > 0) {
            words += inGerman(number / 1000) + "tausend";
            number %= 1000;

        }
        // check if number is divisible by 1 hundred
        if ((number / 100) > 0) {
            words += inGerman(number / 100) + "hundert";
            number %= 100;
        }

        if (number > 0) {
            // check if number is within teens
            if (number < 20) {
                // fetch the appropriate value from unit array
                words += unitsArray[number];
            } else {
                // fetch the appropriate value from tens array
                words += unitsArray[number % 10];
                if ((number % 10) > 0) {
                    words += "und" + tensArray[number / 10];
                }
            }
        }

        return words;
    }
}
e4eetjau

e4eetjau1#

除了没有意义的while语句和未使用的while语句外,代码还不错 static int einer .
可以在unitsarray中包含“null”和“ein”(而不是“eins”),并删除while语句。然后将“ingerman”更改为私有方法“internalingerman”,并处理特殊情况1(可能还有0?你自己看看)用一种新的公共ingerman方法,比如:

public String inGerman(int number) {
    return number == 1 ? "eins" : internalInGerman(number);
}
jq6vz3qz

jq6vz3qz2#

@乔基姆·丹尼尔森是对的。你不能打电话 inGerman 与值递归 1 因为该方法无法判断“ein”或“eins”将在单词中的何处结束。
这些行都可以生成值 1 总有一天 einsunitsArray :

number %= 1000000;
number %= 1000;
number %= 100;

如果你想像我一样采取偷懒的方法,你可以代替我 einseinunitsArray 然后对字符串调用此方法:

inGerman(number).replaceAll( "ein$", "eins");

相关问题