Showing posts with label Spelling An Integer In Chinese PinYin. Show all posts
Showing posts with label Spelling An Integer In Chinese PinYin. Show all posts

Saturday, April 16, 2016

Java Program: Spelling An Integer In Chinese PinYin

The program is to input an integer, whose scope is [-100000, 100000], then, printing out every digit of this integer in Chinese PinYin.

For instance, if the input is 1234, then the output should be as following:

yi er san si

Note that there is a space between the Pinyin of every two digits, but there is no space behind the last digit. When encountering a negative number, add the "fu" at the beginning of the output. For example, -2341 should be output as:

fu er san si yi

Have you had a try?Here is my program.

//Spelling An Integer In Chinese PinYin
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int number = in.nextInt(), digit = 0;
        if (number>=-100000&&number<=100000)
        {
            if (number == 0)
                System.out.print("ling");
            else
            {
                if (number < 0)
                {
                    System.out.print("fu ");
                    number = -number;
                }
                int temp = number;
                while (temp > 0)
                {
                    temp = temp/10;
                    digit++;
                }
                do
                {
                    switch (number/(int)(Math.pow(10, digit-1)))
                    {
                    case 0: System.out.print("ling");
                            break;
                    case 1: System.out.print("yi");
                            break;
                    case 2: System.out.print("er");
                            break;
                    case 3: System.out.print("san");
                            break;
                    case 4: System.out.print("si");
                            break;
                    case 5: System.out.print("wu");
                            break;
                    case 6: System.out.print("liu");
                            break;
                    case 7: System.out.print("qi");
                            break;
                    case 8: System.out.print("ba");
                            break;
                    case 9: System.out.print("jiu");
                    }
                    if (digit > 1)
                        System.out.print(" ");
                    number -= number/(int)(Math.pow(10, digit-1))*(int)(Math.pow(10, digit-1));
                    digit--;
                } while (digit > 0);
            }
        }
    }
}