睡不着,写了个数羊小程序

最多数99999只羊,数多了电脑也累

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 public class CountingSheep {
 5 
 6     private static String[] units = {"","十","百","千","万"};
 7     private static Map<Integer,String> numMap = new HashMap<>();
 8 
 9     static {
10         numMap.put(1,"一");
11         numMap.put(2,"二");   numMap.put(3,"三");
12         numMap.put(4,"四");   numMap.put(5,"五");
13         numMap.put(6,"六");   numMap.put(7,"七");
14         numMap.put(8,"八");   numMap.put(9,"九");
15     }
16 
17     private String readAs(int num) {
18         if(num >= 100000) return "羊太多了";
19         if(num >= 10 && num < 20) {
20             if(num == 10) return "十";
21             else {
22                 return "十" + numMap.get(num % 10);
23             }
24         }
25         StringBuilder res = new StringBuilder();
26         int indexOfUnits = 0;
27         while (num > 0) {
28             int c = num % 10;
29             if(c != 0) {
30                 res.insert(0,numMap.get(c) + units[indexOfUnits]);
31             }else {
32                 if(res.length() != 0 && !res.substring(0,1).equals("零")) {
33                     res.insert(0,"零");
34                 }
35             }
36             indexOfUnits += 1;
37             num /= 10;
38         }
39         return res.toString();
40     }
41 
42     public static void main(String[] args) {
43         int numOfSheep = 99999;
44         CountingSheep countingSheep = new CountingSheep();
45         for (int i=1; i<=numOfSheep; i++) {
46             System.out.println(countingSheep.readAs(i)+"只羊");
47         }
48     }
49 }
原文地址:https://www.cnblogs.com/za-chen/p/14728762.html