java - 如何从 .t​​xt 文件中读取数字并以单字数字的形式打印出来? IE。 30= 三个零 1= 一

标签 java arrays string exception file-io

一位 friend 提到“实用程序类 NumberTranslator”,但我不知道如何使用它。

输入将是一个由格式如下的数字组成的文件:

30 1 3 150

3 6 30

5 6 9

90

输出应该是:

30 : three zero

1 : one

3 : three

150 : one five zero

最佳答案

这应该可以解决问题:

1) 在文件未处理时使用 Scanner 读取下一个 int

2)将int转换为字符数组

3)对于char数组中的每个元素,使用HashMap获取value,其中key为Character,value为word

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public class DigitsConverter{

    // this will have dictionary relation between digits and words
    private static final Map<Character,String> words = new HashMap<>();

    // can use String array instead of Map as suggested in comments
    private static final String[] alsoWords =  {"zero","one","two", "three", "four", "five", "six", "seven", "eight", "nine"}

    // provide mapping of digits to words
    static {

        words.put('0', "zero");
        words.put('1', "one");
        words.put('2', "two");
        words.put('3', "three");
        words.put('4', "four");
        words.put('5', "five");
        words.put('6', "six");
        words.put('7', "seven");
        words.put('8', "eight");
        words.put('9', "nine");
    }


       public static void main(String args[]) throws FileNotFoundException {

           Scanner scanner = new Scanner(new File("../SomeFile"));

           while (scanner.hasNextInt()) {

               char[] chars = ("" + scanner.nextInt()).toCharArray();

               System.out.print(String.valueOf(chars) +": ");

               // for each digit in a given number
               for (char digit: chars) {

                  // print word for that digit
                  System.out.print(words.get(digit) + " ");

                  // if String array is used instead of Map
                  System.out.print(alsoWords[((int)digit- 48)] + " ");

               }
               System.out.println();
           }

           scanner.close();

       }
    }

编辑

用字符串数组添加了 Pshemo 的想法。

关于java - 如何从 .t​​xt 文件中读取数字并以单字数字的形式打印出来? IE。 30= 三个零 1= 一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062099/

相关文章:

java - 将字节写入文件而不删除现有字节

java - 我的套接字应用程序停止工作 - 如何修复它?

java - 包含多个 "keys"的列表对象

c++ - 如何反转AC风格的琴弦

java - 部分字符串匹配

java - 无法运行从 Java 动态生成的批处理文件

java - 创建 Java 类

arrays - 在函数中向数组添加元素,但数组仍为空

arrays - 在 Awk 中使用多个数组而不重复代码

javascript - 尝试 .replace() 但没有成功