//類庫使用案例分析
import java.util.Random ;
import java.util.Arrays ;
import java.util.regex.Matcher ;
import java.util.regex.Pattern ;
public class NewDemo {
public static void main(String[] args) {
//StringBuffer類的使用
StringBuffer buf = new StringBuffer() ;
for(int x = 'a' ; x <= 'z' ; x ++) {
buf.append((char)x) ;
}
buf.reverse().delete(0, 5) ; // 内容反轉(逆序),并删除前5個字母
System.out.println(buf) ;
//利用Random類産生5個1~30之間的實際整數
int result [] = NumberFactory.creat(5, 30) ;
System.out.println(Arrays.toString(result));
//通過指令參數實作Email位址的輸入,并用正規表達式驗證該位址是否正确
if(args.length != 1) {
System.out.println("程式執行錯誤,請輸入初始化參數!") ;
System.exit(1) ; //系統退出
}
String email = args[0] ;
if(Validator.isEmail(email)) {
System.out.println("輸入正确!") ;
}else {
System.out.println("輸入錯誤!") ;
}
//利用實際數模拟抛硬币操作,并統計正反面出現的次數
System.out.println(NumberFactory.throwCoin(1000)) ;
//判斷給定的IP位址是否為合法IP位址
System.out.println(Validator.validateIP("192.168.16.2")) ;
//拆分HTML代碼
String str = "<textarea rows=\"3\" cols=\"20\">" ;
String regex = "\\w+=\"[a-zA-Z0-9,\\+]+\"" ;
Matcher matcher = Pattern.compile(regex).matcher(str) ;
while(matcher.find()) {
String temp = matcher.group(0) ;
String result1 [] = temp.split("=") ;
System.out.println(result1[0] + "\t" + result1[1].replaceAll("=", " ")) ;
}
}
}
class Validator {
private Validator() {} ;
public static boolean isEmail(String email) {
if(email == null || "".equals(email)) {
return false ;
}
String regex = "\\w+@\\w+\\.\\w+" ;
return email.matches(regex) ;
}
public static boolean validateIP(String ip) {
if(ip == null || "".equals(ip)) {
return false ;
}
String regex = "([12]?[0-9]?[0-9]\\.){3}([12]?[0-9]?[0-9])" ;
if(ip.matches(regex)) {
String result [] = ip.split("\\.") ;
for(int x = 0 ; x < result.length ; x ++) {
int temp = Integer.parseInt(result[x]) ;
if(temp > 255) {
return false ;
}else {
return true;
}
}
}
return true ;
}
}
class NumberFactory {
private static Random random = new Random() ; //類對象執行個體化
public static int [] creat(int len, int number) {
int data [] = new int [len] ;
int foot = 0 ;
while (foot < data.length) {
int num = random.nextInt(number) ;
if(num != 0) {
data[foot ++] = num ;
}
}
return data ;
}
public static String throwCoin(int num) {
int front = 0 ; //儲存正面次數
int back = 0 ; //儲存反面次數
for(int x = 0 ; x < num ; x ++) {
int temp = random.nextInt(2) ;
if(temp == 0) {
front ++ ;
}else {
back ++ ;
}
}
return "正面次數:" + front + ",反面次數:" + back ;
}
}
//國際化程式、對象數組的比較