将0-999的整数转化为对应的英文
Posted 勇闯天涯zfc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将0-999的整数转化为对应的英文相关的知识,希望对你有一定的参考价值。
将0-999的整数转化为对应的英文
一、源代码:EnglishNumberFormatter.java
1 package cn.com.zfc.example; 2 3 import java.util.Scanner; 4 5 /** 6 * 将0-999的整数转化为对应的英文 7 * 8 * @author zfc 9 * 10 */ 11 public class EnglishNumberFormatter { 12 private static final String[] BITS = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT,", "NINE", 13 "TEN" }; 14 private static final String[] TEENS = { "ELEVEN", "TWELF", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVETEEN", 15 "EIGHTEEN", "NIGHTEEN" }; 16 private static final String[] TIES = { "TWENTY", "THRITY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", 17 "NINETY" }; 18 19 public static void main(String[] args) { 20 Scanner scanner = new Scanner(System.in); 21 System.out.print("Please type a number between 0 and 999: "); 22 int num = scanner.nextInt(); 23 scanner.close(); 24 String english = toEnglish(num); 25 System.out.println(english); 26 } 27 28 private static String toEnglish(int num) { 29 if (num == 0) { 30 return "Zero"; 31 } 32 StringBuffer buffer = new StringBuffer(); 33 if (num >= 100) { 34 buffer.append(pickHunder(num)); 35 if (num % 100 != 0) { 36 buffer.append(" AND "); 37 } 38 num -= (num / 100) * 100; 39 } 40 boolean largerThan20 = false; 41 if (num >= 20) { 42 largerThan20 = true; 43 buffer.append(pickTies(num)); 44 num -= (num / 10) * 10; 45 } 46 if (!largerThan20 && num > 10) { 47 buffer.append(pickTeens(num)); 48 num = 0; 49 } 50 if (num > 0) { 51 String bit = pickBits(num); 52 if (largerThan20) { 53 buffer.append(" "); 54 } 55 buffer.append(bit); 56 } 57 return buffer.toString(); 58 } 59 60 private static String pickHunder(int num) { 61 int hunder = num / 100; 62 return BITS[hunder - 1] + " HUNDER"; 63 } 64 65 private static String pickTies(int num) { 66 int ties = num / 10; 67 return TIES[ties - 2]; 68 } 69 70 private static String pickTeens(int num) { 71 return TEENS[num - 11]; 72 } 73 74 private static String pickBits(int num) { 75 return BITS[num - 1]; 76 } 77 }
二、运行效果
以上是关于将0-999的整数转化为对应的英文的主要内容,如果未能解决你的问题,请参考以下文章