java第五周总结
之前基于面向對象及邏輯算法實現過動態日歷,發現要寫很多邏輯判斷或者算法,現在基于Calendar實現動態日歷,底層已經完成了很多算法及判斷,大量的減少了代碼量。
public class CalendarDemo {public static void main(String[] args) {Calendar c = Calendar.getInstance();Scanner sc = new Scanner(System.in);System.out.println("今年輸入那一年");int year = sc.nextInt();System.out.println("今年輸入那一月");int month = sc.nextInt() - 1;c.set(Calendar.MONTH, month);c.set(Calendar.YEAR, year);System.out.println("=====================[" + year + "年" + (month + 1) + "月]======================");System.out.println("一\t二\t三\t四\t五\t六\t日");int i = c.getActualMaximum(Calendar.DAY_OF_MONTH);int space = c.get(Calendar.DAY_OF_WEEK) - 1;for (int j = 0; j <= space; j++) {System.out.print("\t");}for (int j = 1; j <= i; j++) {if ((space + j) % 7 == 0) {System.out.println();}System.out.print(j + "\t");}正則表達式
正則表達式是一組由字母和符號組成的特殊文本, 它可以用來從文本中找出滿足你想要的格式的句子
簡單案例:
String a = "13567845635"; //判斷兩個字符串是否完全一致 System.out.println(a.equals("13567845634")); //判斷當前String對象是否匹配給定的正則表達式( 匹配手機號格式字符串) System.out.println(a.matches("^1\\d{10}$"));題目:在歌詞里找關鍵詞
public static void main(String[] args) {Pattern p = Pattern.compile("月亮");Matcher m = p.matcher( "看月亮爬上來 看月亮爬上來 看月亮爬上來 失眠的夜漫漫飄過來 想念的心沒什么阻礙好像聽說最近你也在失眠 一個人發呆 喜歡你笑得像個小孩 想每天和你粘在一塊 聽一首老歌就會流淚的女孩 沒我可怎么辦 我們一起看月亮爬上來 你也在失眠想著你的最愛 我們一起看月亮爬上來 你也在失眠想有美好未來 我們一起看月亮爬上來 你也在失眠誰在為誰等待 我們一起看月亮爬上來 失眠的夜愛的人會不會向你告白 喜歡你笑得像個小孩 想每天和你粘在一塊 聽一首老歌就會流淚的女孩 沒我可怎么辦 我們一起看 月亮爬上來 你也在失眠想著你的最愛我們一起看 月亮爬上來 你也在失眠想有美好未來 我們一起看 月亮爬上來 你也在失眠誰在為誰等待 我們一起看 月亮爬上來 失眠的夜愛的人會不會向你告白 ");int count = 0;while(m.find()) {count++;}System.out.println(count);}基于文件讀取完成代碼行數的查看
private static ArrayList<File> javaFiles = new ArrayList<File>();/*** 讀取指定的目錄獲取所有的java文件的絕對路徑* @param dir* @return*/public static void readAndStoreJavaFile(File dir) {File[] files = dir.listFiles();if(Objects.nonNull(files)) {for (File f : files) {if(f.isDirectory()) {readAndStoreJavaFile(f);}//獲取所有的java文件if(f.getName().endsWith(".java")) {//將java文件加入容器中javaFiles.add(f);}}}} /*** 讀取指定的java文件并返回文件中的代碼內容* @param file* @return*/public static String readJavaFile(File file) {StringBuffer sb = new StringBuffer();BufferedReader br = null;try {InputStream is = new FileInputStream(file);br = new BufferedReader(new InputStreamReader(is));String str = "";while((str = br.readLine()) != null) {sb.append(str).append("\n");}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {try {if(br != null)br.close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}//總代碼行數static final Pattern REGEX_CODE_LINES = Pattern.compile("\\n");//空白代碼行數static final Pattern WHITE_CODE_LINES = Pattern.compile("\\n\\s*\\n");public static void main(String[] args) {int i = 0;int j = 0;File dir = new File("C:\\eclipse-workspace");readAndStoreJavaFile(dir);for (File file : javaFiles) {String code = readJavaFile(file);Matcher m = REGEX_CODE_LINES.matcher(code);Matcher m1 = WHITE_CODE_LINES.matcher(code);while(m.find()) {i++;}while(m1.find()) {j++;}}System.out.println("總代碼數為:"+i);System.out.println("空白代碼數為:"+j);}運行結果:
正則表達式三種模式
- 貪婪模式:貪婪模式即從匹配到的位置開始一直往后依次搜索,并且會回溯
- 獨占模式:一直往后搜索會將后續的所有字符串進行匹配
- 懶惰模式:找到即結束
基于面向對象及正則完成的通訊錄
聯系人類:
public class Contact {/**編號*/private int id;private String phone;private String name;private int qq;private String mail;//構造器//getter/setter //toString()}}聯系人管理類
package com.day02;import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;import org.omg.CORBA.CODESET_INCOMPATIBLE;public class ContactManage {/** 初始化一個集合 */static ArrayList<Contact> list = new ArrayList<Contact>();/** 電話正則表達式 */String regex = "^1[356789]\\d{9}";/*** 添加聯系人的方法* @param c* @return* @throws MyException */public boolean addContact(Contact c) {return list.add(c);}/** 根據姓名或者手機號查找聯系人 */public Contact findContact(String str) {for (Contact c : list) {if (str.matches(regex) || str.equals(c.getName())) {return c;}}return null;}public List<Contact> findAllContact(){return list;}/*** 刪除聯系人* @param id*/public boolean delContact(int id) {Integer i = Integer.valueOf(getIndex(id));return list.remove(i);}/*** 根據id找到集合中元素索引* @param id* @return*/public int getIndex(int id) {for (int i = 0; i < list.size(); i++) {if(id == list.get(i).getId()) {return i;}}return -1; } }測試類:
public class Test {private Scanner sc = new Scanner(System.in);private ContactManage c = new ContactManage();public void menu() {p("******************歡迎使用通訊錄******************");p("*\t\t[0]退出\t\t\t\t*");p("*\t\t[1]添加聯系人\t\t\t*");p("*\t\t[2]刪除聯系人\t\t\t*");p("*\t\t[3]根據姓名查詢聯系人\t\t*");p("*\t\t[4]根據電話查詢聯系人\t\t*");p("*\t\t[5]顯示全部聯系人\t\t\t*");p("*************************************************");stare();}private void stare() {System.out.println("請輸入正確的指令");String input = sc.next();if (!input.matches("[0-5]")) {stare();}switch (input) {case "1":addContact();break;case "2":delContact();break;case "3":findContact();break;case "4":findContactByName();break;case "5": findAllContact();break;case "0":p("謝謝使用,再見");System.exit(0);break;}}/*** 查詢全部聯系人*/private void findAllContact() {List<Contact> list = c.findAllContact();for (Contact contact : list) {p(contact);}menu();}/*** 刪除聯系人*/private void delContact() {p("根據編號刪除指定編號的聯系人");String input = sc.next();if (!input.matches("\\d.+")) {p("請輸入數字");delContact();} else {if (!c.delContact(Integer.parseInt(input))) {p("刪除成功");menu();}else {p("沒有該聯系人");menu();}}}/** 根據姓名查詢聯系人 */private void findContactByName() {p("請輸入你要查詢的關鍵詞");String input = sc.next();if (!input.matches(".+")) {p("信息有誤!");findContact();} else {p(c.findContact(input));menu();}}/** 根據電話查詢聯系人 */private void findContact() {p("請輸入你要查詢的關鍵詞");String input = sc.next();if (!input.matches("1\\d{10}")) {p("信息有誤!");findContact();} else {p(c.findContact(input));menu();}}private void addContact() {// int id, String phone, String name, int qq, String mailp("請輸入聯系人信息(id/電話/姓名/qq/郵箱/)");String input = sc.next();if (!input.matches("\\d+/1\\d{10}/.+/\\d{4,11}/[1-9]\\d{5,11}@qq\\.com")) {p("請輸入正確的聯系人信息");addContact();} else {String[] split = input.split("/");Contact contact = new Contact(Integer.parseInt(split[0]), split[1], split[2], Integer.parseInt(split[3]),split[4]);if (c.addContact(contact)) {p("添加成功");menu();} else {p("添加失敗");addContact();}}}private void p(Object msg) {System.out.println(msg);}public static void main(String[] args) {new Test().menu();}
集合
Collection是頂層接口,Set(無序集合)和List(有序集合)都是從Collection實現而來。
List:有序且可以重復
list集合的三種實現類
- ArrayList
- LinkedList
- Vector
ArrayList、LinkedList、Vector的區別
首先,它們都屬于List接口的實現,是基于數組及數組拷貝的實現,但Vector屬于老式集合(jdk1.0),并且屬于線程安全的實現,容量是通過三木運算進行兩倍擴充的。而ArrayList和LinkedList都屬于線程不安全的實現,ArrayList也是基于數組及數組拷貝的方式完成的實現,容量是通過位運算完成1.5倍的擴充。ArrayList數據查詢較快,修改較慢。LinkedList基于雙向鏈表實現的,數據查詢較慢,但修改較快。
List list = new ArrayList();list.add("jack");list.add("faker");list.add("cike");list.add("rose");list.add("tarloy");ListIterator it = list.listIterator();while(it.hasNext()) {System.out.println(it.next());}//逆向排序System.out.println("==================");while(it.hasPrevious()) {System.out.println(it.previous());} LinkedList list = new LinkedList();list.add("yuxia");list.add("rose");list.add("jerry");list.add("faker");list.add("theshy");list.add("sindy");list.addFirst("baby");list.addLast("JustBir");Collections.sort(list);System.out.println(list);list.clear();Iterator it = list.iterator();while(it.hasNext()) {System.out.println(it.next());}集合排序
Collections中用于實現集合排序的方法有如下兩個:
Comparable & Compartor
User類
public class User {private String name;private int id;private Date bir;private double score;public User(String name, int id, Date bir, double score) {super();this.name = name;this.id = id;this.bir = bir;this.score = score;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Date getBir() {return bir;}public void setBir(Date bir) {this.bir = bir;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}測試類
public static void main(String[] args) {List<User> list = new ArrayList();list.add(new User("李四", 1002, new Date(103, 11, 7), 98.2));list.add(new User("王五", 1003, new Date(99, 7, 1), 43.1));list.add(new User("來福", 1004, new Date(100, 7, 1), 85.3));list.add(new User("旺財", 1005, new Date(102, 8, 2), 54.1));// 方法一Collections.sort(list, new Comparator<User>() {@Overridepublic int compare(User o1, User o2) {// 分數的高低進行排序return (int) (o1.getScore() - o2.getScore());}});for (Object object : list) {System.out.println(object);}System.out.println("=============方法二=============");// 直接用list對象調list.sort(new Comparator<User>() {@Overridepublic int compare(User o1, User o2) {// 對id進行排序return o2.getId() - o1.getId();}});for (Object object : list) {System.out.println(object);}// 方法三,自己創建類實現comparator接口System.out.println("==============方法三=============");MyComparator comparator = new MyComparator();Collections.sort(list, comparator);for (Object object : list) {System.out.println(object);}}運行結果
中文排序
導入此jar包
運行結果
總結
- 上一篇: 高斯基函数线性组合回归练习——sklea
- 下一篇: python布尔类型的两个值_布尔人有两