首页 > 解决方案 > 如何从这些字符中获取整数值?

问题描述

“我想通过用户输入插入字符。然后我需要输出一个与每个字符相似的整数值?

例如:输入 -

thr#e hun#red forty five t#ou#and two hundred th#rty f#ur

输出 -

345234

我试过这个代码。但它显示了一些错误信息。

public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
    String N = input.next();
    int result = Integer.parseInt(N);
    System.out.println(result);

}

}

标签: javatype-conversion

解决方案


如果这是我的项目,我会尝试将尖字符 (#)更改 为所有英文字母的字符,看看哪个最适合单词,然后将输出更改为 letters

示例代码:( 将输入更改为字母名称)

public static void main(String[] args) {
    // input o#e tw# thr#e

    char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    String[] numbers = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"};
    String input = "o#e tw# thr#e";

    String[] words = input.split(" ");
    for (int i = 0; i < words.length; i++) { // reads one by one the words
        for (int j = 0; j < alphabet.length; j++) { checks if the character[j] fits the word
            for (int k = 0; k < numbers.length; k++) { // checks if the numbers contain that string
                if (numbers[k].equalsIgnoreCase(words[i].replace('#', alphabet[j])))
                    words[i] = numbers[k];
            }
        }
    }
}

推荐阅读