第14 章 : 類庫使用案例分析
59 StringBuffer使用
使用StringBuffer追加26個小寫字母。逆序輸出,并删除前5個字元
StringBuffer允許修改 String不允許修改
StringBuffer buff = new StringBuffer();
for(int i = 'a'; i<='z'; i++){
buff.append((char)i);
}
System.out.println(buff.reverse().delete(0, 5));
// utsrqponmlkjihgfedcba
60 随機數組
Rondom 産生5個[1, 30]之間随機數
import java.util.Arrays;
import java.util.Random;
class NumberFactory{
private static Random random = new Random();
public static int[] getRandomList(int num){
int[] list = new int[num];
int foot = 0;
while (foot < num) {
int value = random.nextInt(31);
if (value !=0 ){
list[foot++] = value;
}
}
return list;
}
}
class Demo{
public static void main(String[] args) {
int[] list = NumberFactory.getRandomList(5);
System.out.println(Arrays.toString(list));
// [27, 3, 9, 4, 12]
}
}
61 Email驗證
class Validator{
public static boolean isEmail(String email){
if(email == null || "".equals(email)){
return false;
}
String regex = "\\w+@\\w+\\.\\w+";
return email.matches(regex);
}
}
class Demo{
public static void main(String[] args) {
System.out.println(Validator.isEmail("[email protected]"));
// true
}
}
62 扔硬币
0-1随機數模拟投擲硬币 1000次
import java.util.Random;
class Coin{
private int front;
private int back;
private Random random = new Random();
public void throwCoin(int num){
for (int i = 0; i < num; i++) {
int value = random.nextInt(2);
if (value == 0){
this.front ++;
} else{
this.back ++;
}
}
}
public int getFront() {
return this.front;
}
public int getBack() {
return this.back;
}
}
class Demo{
public static void main(String[] args) {
Coin coin = new Coin();
coin.throwCoin(1000);
System.out.println("正面: " + coin.getFront());
System.out.println("背面: " + coin.getBack());
// 正面: 495
// 背面: 505
}
}
63 IP驗證
eg: 127.0.0.1
第一位 [12]?
第二位 [0-9]{0, 2}
import java.util.Random;
class Validator {
public static boolean isIp(String ip) {
String regex = "(\\d{1,3}\\.){3}\\d{1,3}";
if (!ip.matches(regex)) {
return false;
}
String[] list = ip.split("\\.");
for (String str : list) {
int num = Integer.parseInt(str);
if (num > 255 || !str.equals(Integer.toString(num))) {
return false;
}
}
return true;
}
}
class Demo {
public static void main(String[] args) {
System.out.println(Validator.isIp("127.0.0")); // false
System.out.println(Validator.isIp("127.0.0.1")); // true
System.out.println(Validator.isIp("255.255.255.255")); // true
System.out.println(Validator.isIp("255.255.255.666")); // false
System.out.println(Validator.isIp("255.255.001.1")); // false
}
}
64 HTML拆分
<font face="Arial,Serif" size="+2" color="red"></font>
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo {
public static void main(String[] args) {
String html = "<font face=\"Arial,Serif\" size=\"+2\" color=\"red\"></font>";
String regex = "\\w+=\"[a-zA-Z0-9,\\+]+\"";
Matcher matcher = Pattern.compile(regex).matcher(html);
while (matcher.find()){
String temp = matcher.group(0);
String[] result = temp.split("=");
System.out.println(result[0] + "\t" + result[1].replaceAll("\"", ""));
/**
* face Arial,Serif
* size +2
* color red
*/
}
}
}
65 國家代碼
實作國際化應用
輸入國家代号,調用資源檔案
3個資源檔案
# message.properties
info=預設資源
# message_en_US.properties
info=英文資源
# message_zh_CN.properties
info=中文資源
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
class MessageUtil {
// 将固定的内容定義為常量
private static final String CHINA = "cn";
private static final String ENGLISH = "en";
private static final String BASENAME = "message";
private static final String KEY = "info";
public static String getMessage(String country) throws UnsupportedEncodingException {
Locale locale = getLocale(country);
if (locale == null) {
return null;
} else {
ResourceBundle bundle = ResourceBundle.getBundle(BASENAME, locale);
return new String(bundle.getString(KEY).getBytes("ISO-8859-1"), "utf-8");
}
}
private static Locale getLocale(String country) {
switch (country) {
case CHINA:
return new Locale("zh", "CN");
case ENGLISH:
return new Locale("en", "US");
default:
return null;
}
}
}
class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
if (args.length < 1) {
System.out.println("請輸入:cn 或者 en");
System.exit(1);
}
System.out.println(MessageUtil.getMessage(args[0]));
// 中文資源
}
}
66 學生資訊比較
先用成績比較,如果相同按年齡比較
資料結構
姓名:年齡:成績|姓名:年齡:成績
eg:
張三:21:98|李四:23:96|王五:24:94
結構化的字元串處理
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
class Student implements Comparable<Student>{
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student other) {
// 先用成績比較,再用年齡比較
if(this.score > other.score){
return 1;
} else if (this.score < other.score){
return -1;
} else{
return this.age - other.age;
}
}
@Override
public String toString() {
return "Student{" + name + ',' + age + ", " + score + "}";
}
}
class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
String data = "張三:21:98|李四:23:96|王五:24:94";
String[] list = data.split("\\|");
Student[] students = new Student[list.length];
for (int i = 0; i < list.length; i++) {
String[] temp = list[i].split(":");
students[i] = new Student(temp[0], Integer.parseInt(temp[1]), Double.parseDouble(temp[2]));
}
Arrays.sort(students);
System.out.println(Arrays.toString(students));
// [Student{王五,24, 94.0}, Student{李四,23, 96.0}, Student{張三,21, 98.0}]
}
}