[Java] 類庫例題

例1 字符串操做html

定義一個StringBuffer類對象,而後經過append()方法向對象中添加26個小寫字母,每次只添加一次,共添加26次,而後按逆序方式輸出,而且能夠刪除前5個字符java

  • 面向過程實現
 1 public class TestDemo {
 2     public static void main(String[] args) throws Exception{
 3         StringBuffer buffer = new StringBuffer();
 4         for(int x = 'a' ; x <= 'z' ; x++) {
 5             buffer.append((char)x);
 6         }
 7         System.out.println("[初始化數據]" + buffer);
 8         System.out.println("[逆序輸出]" + buffer.reverse());
 9         System.out.println("[刪除前五個字符]" + buffer.delete(0, 5));
10     }
11 }
View Code
  • 面向對象實現(接口先行--子類實現--工廠解耦)
 1 interface IContent{
 2     public String content();
 3     public String reverse();
 4     public String delete(int index);
 5 }
 6 class StringContent implements IContent{
 7     private StringBuffer buffer = new StringBuffer();
 8     public StringContent() {
 9         for(int x = 'a' ; x <= 'z' ; x++) {
10             buffer.append((char)x);
11         }
12     }
13     @Override
14     public String content() {
15         return this.buffer.toString();
16     }
17     @Override
18     public String reverse() {
19         return this.buffer.reverse().toString();
20     }
21     @Override
22     public String delete(int index) {
23         return this.buffer.delete(0, index).toString();
24     }
25 }
26 class Factory{
27     private Factory() {}
28     public static IContent getInstance() {
29         return new StringContent();
30     }
31 }
32 public class TestDemo {
33     public static void main(String[] args) throws Exception{
34         IContent content = Factory.getInstance();
35         System.out.println("[初始化數據]" + content.content());
36         System.out.println("[逆序輸出]" + content.reverse());
37         System.out.println("[刪除前五個字符]" + content.delete(5));
38     }
39 }
View Code

  • 先定義出公共處理標準,隨後依據此標準進行項目的具體實現
  • 對於接口子類的獲取採用工廠模式 

例2 生成隨機數正則表達式

利用Random類產生5個1~30之間(包括1和30)的隨機整數數組

  • 接口:描述最終目的
  • 異常類:繼承RuntimeException,業務異常,不但願此異常直接出如今方法的定義聲明處(若是繼承Exception會強制處理)

 1 package javaSE;
 2 
 3 import java.util.Arrays;
 4 import java.util.Random;
 5 
 6 interface INumber{
 7     public int[] getData();
 8 }
 9 class InvalidArrayLengthException extends RuntimeException{
10     public InvalidArrayLengthException() {}
11     public InvalidArrayLengthException(String str) {
12         super(str);
13     }
14 }
15 class RandomNumber implements INumber{
16     private int data[];
17     public RandomNumber() {
18         this(3);
19     }
20     public RandomNumber(int len) {
21         if(len <= 0) {
22             throw new InvalidArrayLengthException("數組長度不正確!");
23         }
24         this.data = new int[len];
25         this.createRandom();
26     }
27     public void createRandom() {
28         Random random = new Random();
29         for(int x = 0 ; x < this.data.length; x++) {
30             this.data[x] = random.nextInt(30) + 1;
31         }
32     }
33     @Override
34     public int[] getData() {
35         return this.data;
36     }
37 }
38 class Factory{
39     private Factory() {}
40     public static INumber getInstance(int ...args) {
41         if(args.length == 0) {
42             return new RandomNumber();
43         }else {
44             return new RandomNumber(args[0]);
45         }
46     }
47 }
48 public class TestDemo {
49     public static void main(String[] args) throws Exception{
50         INumber content = Factory.getInstance(5);
51         System.out.println(Arrays.toString(content.getData()));
52     }
53 }
View Code

例3 Email驗證app

輸入一個Email地址,用正則表達式驗證該Email是否正確dom

 1 import java.util.Arrays;
 2 import java.util.Random;
 3 
 4 interface IValidator{
 5     public boolean test() ;
 6 }
 7 class EmailValidator implements IValidator{
 8     public static final String DEFAULT_EMAIL_REGEX = "\\w+@\\w+\\.\\w+";
 9     private String regex;
10     private String content;
11     public EmailValidator(String content) {
12         this(content,DEFAULT_EMAIL_REGEX);
13         this.content = content;
14         this.regex = DEFAULT_EMAIL_REGEX;
15     }
16     public EmailValidator(String content,String regex) {
17         this.content = content;
18         this.regex = regex;
19     }
20     @Override
21     public boolean test() {
22         if(this.content == null || "".equals(this.content)) {
23             return false;
24         }
25         return this.content.matches(this.regex);
26     }
27 }
28 class Factory{
29     private Factory() {}
30     public static IValidator getInstance(String content,String ...regex) {
31         if(regex.length == 0) {
32             return new EmailValidator(content);
33         }else {
34             return new EmailValidator(content,regex[0]);
35         }
36     }
37 }
38 public class TestDemo {
39     public static void main(String[] args) throws Exception{
40         {IValidator validator = Factory.getInstance("muyan@yootk.com");
41         System.out.println(validator.test() ? "驗證經過":"Email數據輸入錯誤");}
42         {IValidator validator = Factory.getInstance("muyan@yootk.org",
43                 "[a-zA-Z][a-zA-Z0-9_\\-\\.]+@\\w+\\.(com|com\\.cn|net\\.cn|gov|edu|org)");
44         System.out.println(validator.test() ? "驗證經過":"Email數據輸入錯誤");}
45     }
46 }
View Code
  • 便可使用默認的正則表達式,也可根據須要擴充

例4 IP地址驗證ide

編寫正則表達式,判斷給定的IP地址是否合法 this

 1 interface IValidator{
 2     public boolean test() ;
 3 }
 4 class IPHostValidator implements IValidator{
 5     public static final String DEFAULT_EMAIL_REGEX = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
 6     private String regex;
 7     private String content;
 8     public IPHostValidator(String content) {
 9         this(content, DEFAULT_EMAIL_REGEX);
10     }
11     public IPHostValidator(String content,String regex) {
12         this.content = content;
13         this.regex = regex;
14     }
15     @Override
16     public boolean test() {
17         if(this.content == null || "".equals(this.content)) {
18             return false;
19         }
20         if("0.0.0.0".equals(this.content)||"255.255.255.255".equals(this.content)) {
21             return false;
22         }
23         return this.content.matches(this.regex);
24     }
25 }
26 class Factory{
27     private Factory() {}
28     public static IValidator getInstance(String content,String ...regex) {
29         if(regex.length == 0) {
30             return new IPHostValidator(content);
31         }else {
32             return new IPHostValidator(content,regex[0]);
33         }
34     }
35 }
36 public class TestDemo {
37     public static void main(String[] args) throws Exception{
38         IValidator validator = Factory.getInstance("192.168.1.2");
39         System.out.println(validator.test() ? "驗證經過":"IP數據輸入錯誤");
40     }
41 }
View Code
  • 實際開發中除了核心代碼,最多見的就是數據驗證功能

例5 HTML拆分idea

給定一段HTML代碼:「<font face="Arial,Serif" size="+2" color="red">」,拆分爲spa

face=Arial,Serif

size=+2

color=red

 1 import java.util.regex.Matcher;
 2 import java.util.regex.Pattern;
 3 
 4 interface IStringHandle{
 5     public String[] split();
 6 }
 7 class HTMLStringHandle implements IStringHandle{
 8     private String content;
 9     private String regex;
10     public HTMLStringHandle(String content,String regex) {
11         this.content = content;
12         this.regex = regex;
13     }
14     @Override
15     public String[] split() {
16         Matcher matcher = Pattern.compile(this.regex).matcher(this.content);
17         StringBuffer buffer = new StringBuffer(this.content.length());
18         while(matcher.find()) {
19             String value = matcher.group(0);
20             String temp[] = value.split("=");
21             buffer.append(temp[0]).append(":").append(temp[1].replaceAll("\"","")).append("|");
22         }
23         return buffer.toString().split("\\|");
24     }
25 }
26 class Factory{
27     private Factory() {}
28     public static IStringHandle getInstance(String content,String regex) {
29         return new HTMLStringHandle(content,regex);
30     }
31 }
32 public class TestDemo {
33     public static void main(String[] args) throws Exception{
34         String html = "<font face=\"Arial,Serif\" size=\"+2\" color=\"red\">";
35         String regex = "\\w+=\"[a-zA-Z0-9,\\+]+\"";
36         IStringHandle handle = Factory.getInstance(html, regex);
37         String result[] = handle.split();
38         for(String temp:result) {
39             System.out.println(temp);
40         }
41     }
42 }
View Code

  • 可以使用HTMLParser+XPath 

例6 國際化應用

從命令行輸入國家代號,1表明中國,2表明美國,而後根據不一樣代號調用不一樣的資源文件顯示信息

  • 編寫資源文件 
  • 加載資源文件
  • 經過IMessage接口,根據key獲取數據
 1 import java.util.Locale;
 2 import java.util.ResourceBundle;
 3 
 4 interface IMessage{
 5     public String get(String key);
 6 }
 7 
 8 class ResourceMessage implements IMessage{
 9     private static final String BASE_NAME = "Message";
10     private ResourceBundle resourceBundle;
11     public ResourceMessage(Locale locale){
12         this.resourceBundle = ResourceBundle.getBundle(BASE_NAME,locale);
13     }
14 
15     @Override
16     public String get(String key){
17         try{
18             return this.resourceBundle.getString(key);
19         }catch (Exception e){
20             return null;
21         }
22     }
23 }
24 
25 class ParameterException extends RuntimeException{
26     public ParameterException(){}
27     public ParameterException(String msg){
28         super(msg);
29     }
30 }
31 
32 class Factory{
33     private Factory(){}
34     public static IMessage getInstance(String args[]){
35         if(args.length != 1 || !args[0].matches("\\d")){
36             throw new ParameterException("初始參數配置錯誤,沒法執行");
37         }
38         int select = Integer.parseInt(args[0]);
39         switch (select){
40             case 1:
41                 return new ResourceMessage(Locale.CHINESE);
42             case 2:
43                 return new ResourceMessage(Locale.US);
44             default:
45                 return null;
46         }
47     }
48 }
49 
50 public class YootkDemo {
51     public static void main(String[] args) throws Exception{
52         IMessage message = Factory.getInstance(args);
53         System.out.println(message.get("welcome.info"));
54     }
55 }
View Code

>> Hello 

參考

idea:Maven項目,pom.xml中的resources標籤

https://blog.csdn.net/qq_36134376/article/details/90762263

相關文章
相關標籤/搜索