面试时有一道面试题:要求获取当时时间,并像电子手表那样打印到控制台。
1 import java.text.SimpleDateFormat; 2 import java.time.LocalTime; 3 import java.util.Date; 4 5 /** 6 * 打印时间到控制台 7 * 8 */ 9 public class ConsoleTime { 10 11 public static void main(String[] args) { 12 13 // LocalTime now = LocalTime.now(); 14 // System.out.println(now); 15 // System.out.println(now.getHour() + " " + now.getMinute() + " " + now.getSecond()); 16 17 Date date = new Date(); 18 //yyyy-MM-dd 19 SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");//设置日期格式 20 String str = format.format(date); 21 System.out.println("现在时间:" + str); 22 23 String[] time = getTime(str.split(":")); 24 for (int i=0; i<time.length; i++) { 25 System.out.println(time[i]); 26 } 27 } 28 29 static String[] getTime(String[] array) { 30 String[] strArrays = new String[5]; 31 String str1 = ""; 32 String str2 = ""; 33 String str3 = ""; 34 String str4 = ""; 35 String str5 = ""; 36 37 for (int i=0; i<array.length; i++) { 38 char[] chars = array[i].toCharArray(); 39 for (int a=0; a<chars.length; a++) { 40 switch (chars[a]) { 41 case '0': 42 str1 += " -- "; 43 str2 += " | | "; 44 str3 += " | | "; 45 str4 += " | | "; 46 str5 += " -- "; 47 break; 48 case '1': 49 str1 += " | "; 50 str2 += " | "; 51 str3 += " | "; 52 str4 += " | "; 53 str5 += " | "; 54 break; 55 case '2': 56 str1 += " ---- "; 57 str2 += " | "; 58 str3 += " ---- "; 59 str4 += " | "; 60 str5 += " ---- "; 61 break; 62 case '3': 63 str1 += " ---- "; 64 str2 += " | "; 65 str3 += " ---- "; 66 str4 += " | "; 67 str5 += " ---- "; 68 break; 69 case '4': 70 str1 += " | | "; 71 str2 += " | | "; 72 str3 += " ---- "; 73 str4 += " | "; 74 str5 += " | "; 75 break; 76 case '5': 77 str1 += " ---- "; 78 str2 += " | "; 79 str3 += " ---- "; 80 str4 += " | "; 81 str5 += " ---- "; 82 break; 83 case '6': 84 str1 += " ---- "; 85 str2 += " | "; 86 str3 += " ---- "; 87 str4 += " | | "; 88 str5 += " ---- "; 89 break; 90 case '7': 91 str1 += " ---- "; 92 str2 += " | "; 93 str3 += " | "; 94 str4 += " | "; 95 str5 += " | "; 96 break; 97 case '8': 98 str1 += " ---- "; 99 str2 += " | | "; 100 str3 += " ---- "; 101 str4 += " | | "; 102 str5 += " ---- "; 103 break; 104 case '9': 105 str1 += " ---- "; 106 str2 += " | | "; 107 str3 += " ---- "; 108 str4 += " | "; 109 str5 += " ---- "; 110 break; 111 } 112 } 113 if(i < (array.length-1)) { 114 str1 += " "; 115 str2 += " . "; 116 str3 += " "; 117 str4 += " . "; 118 str5 += " "; 119 } 120 } 121 strArrays[0] = str1; 122 strArrays[1] = str2; 123 strArrays[2] = str3; 124 strArrays[3] = str4; 125 strArrays[4] = str5; 126 return strArrays; 127 } 128 129 }
打印出来的样式: