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

2021/5/4 12:28:52

本文主要是介绍睡不着,写了个数羊小程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最多数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 }

 



这篇关于睡不着,写了个数羊小程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程