PAT 1002 寫出這個數 (20分) java題解

題目網址:PAT 1002 寫出這個數 (20分)

讀入一個正整數 n,計算其各位數字之和,用漢語拼音寫出和的每一位數字。

輸入格式:

每個測試輸入包含 1 個測試用例,即給出自然數 n 的值。這裏保證 n 小於 10的100次方

輸出格式:

在一行內輸出 n 的各位數字之和的每一位,拼音數字間有 1 空格,但一行中最後一個拼音數字後沒有空格。

輸入樣例:

1234567890987654321123456789

輸出樣例:

yi san wu

分析:運用字符數組和循環把輸入數字的結果計算出來,再將結果放入字符數組通過switch方法輸出拼音,最後注意空格的位置。

AC代碼:

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] ch1 = str.toCharArray();
        int sum=0;
        for(int i=0;i<ch1.length;i++){
            sum += ch1[i]-'0';    //char轉int
        }
        String s1 = String.valueOf(sum);
        char[] ch2 = s1.toCharArray();
        for(int i=0;i<ch2.length;i++){
            switch (ch2[i]){
                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");
                    break;
                case ('0'):
                    System.out.print("ling");
                    break;
            }
            if(i!=ch2.length-1){
                System.out.print(" ");
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章