------- android培訓、java培訓、期待與您交流! ----------
14.01 如何校驗一個QQ號碼案例
1 import java.util.Scanner; 2 3 /* 4 * 校驗qq號碼. 5 * 1:要求必須是5-15位數字 6 * 2:0不能開頭 7 * 8 * 分析: 9 * A:鍵盤錄入一個QQ號碼10 * B:寫一個功能實現校驗11 * C:調用功能,輸出結果。12 */13 public class PRactice 14 {15 /**16 * @param args17 */18 public static void main(String[] args) 19 {20 // 創建鍵盤錄入對象21 Scanner sc = new Scanner(System.in);22 System.out.println("請輸入你的QQ號碼:");23 String qq = sc.nextLine();24 25 System.out.println("checkQQ:"+checkQQ(qq));26 }27 /*28 * 寫一個功能實現校驗 29 返回值類型:boolean 參數列表:String qq30 */31 public static boolean checkQQ(String qq) 32 {33 boolean flag = true;34 // 校驗長度35 if (qq.length() >= 5 && qq.length() <= 15) 36 {37 // 0不能開頭38 if (!qq.startsWith("0")) 39 {40 // 必須是數字41 char[] chs = qq.toCharArray();42 for (int x = 0; x < chs.length; x++) 43 {44 char ch = chs[x];45 if (!Character.isDigit(ch)) 46 {47 flag = false;48 break;49 }50 }51 } 52 else 53 {54 flag = false;55 }56 } 57 else 58 {59 flag = false;60 }61 return flag;62 }63 }
14.02 正則表達式的概述和基本使用
正則表達式:是指一個用來描述或者匹配一系列符合某個句法規則的字符串的單個字符串。其實就是一種規則。有自己特殊的應用。
例:
public static boolean checkQQ(String qq) { //return qq.matches("[1-9][0-9]{4,14}"); return qq.matches("[1-9]//d{4,14}");}14.03 正則表達式的組成規則
規則字符在java.util.regex Pattern類中
常見組成規則:
1. 字符
X 字符 x舉例:'a'表示字符a
// 反斜線字符。
/n 新行(換行)符 ('/u000A')
/r 回車符 ('/u000D')
2. 字符類
[abc] a、b 或 c(簡單類)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(范圍)
[0-9] 0到9的字符都包括
3. 預定義字符類
. 任何字符,如果是.字符本身,用 /.表示
/d 數字:[0-9]
/w 單詞字符:[a-zA-Z_0-9],在正則表達式里面單詞必須有這些東西組成
4. 邊界匹配器
^ 行的開頭
$ 行的結尾
/b 單詞邊界,就是不是單詞字符的地方
5. Greedy 數量詞
X? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超過 m 次
14.04 正則表達式的判斷功能
public boolean matches(String regex):
告知此字符串是否匹配給定的正則表達式。
例:校驗手機號的規則
String regex = "1[358]//d{9}";
該正則表達式表示第1位必須是1,第2位可是是358中的任意一位,后9位可以是0~9的任意數字
14.05 校驗郵箱案例
例:String regex = "http://w+@//w{2,6}(//.//w{2,3})+";
規則解釋:[a-zA-Z_0-9]@[a-zA-Z_0-9]2~6次(.[a-zA-Z_0-9]2~3次)多次
14.06 正則表達式的分割功能
public String[] split(String regex):
根據給定正則表達式的匹配拆分此字符串。
14.07 分割功能的小練習
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String s1 = "aa,bb,cc"; 6 String[] str1 = s1.split(","); 7 print(str1); 8 9 String s2 = "aa.bb.cc";10 String[] str2 = s2.split("http://.");11 print(str2);12 13 String s3 = "aa bb cc";14 String[] str3 = s3.split(" +");15 print(str3);16 17 String s4 = "D://Develop//Java//jdk1.7.0_51";18 String[] str4 = s4.split("http:////");19 print(str4);20 }21 public static void print(String[] str)22 {23 for (int i = 0; i < str.length; i++) 24 {25 System.out.print(str[i]+" ");26 }27 System.out.println();28 }29 }運行結果:
aa bb cc aa bb cc aa bb cc D: Develop Java jdk1.7.0_51
14.08 把字符串中的數字排序案例
有如下一個字符串:"91 27 46 38 50"請寫代碼實現最終輸出結果是:"27 38 46 50 91"
分析:
A:定義一個字符串
B:把字符串進行分割,得到一個字符串數組
C:把字符串數組變換成int數組
D:對int數組排序
E:把排序后的int數組再組裝成一個字符串
F:輸出字符串
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String str = "91 27 46 38 50"; 6 String[] strArray = str.split(" "); 7 int[] arr = new int[strArray.length]; 8 for (int i = 0; i < strArray.length; i++) 9 {10 arr[i] = Integer.parseInt(strArray[i]);11 }12 13 for (int i = 0; i < arr.length-1; i++) 14 {15 for (int j = i+1; j < arr.length; j++) 16 {17 if(arr[i] > arr[j])18 {19 int temp = arr[i];20 arr[i] = arr[j];21 arr[j] = temp;22 }23 }24 }25 StringBuilder sb = new StringBuilder();26 sb.append("/"");27 for (int i = 0; i < arr.length; i++) 28 {29 if(i == arr.length-1)30 {31 sb.append(arr[i]+"/"");32 }33 else34 sb.append(arr[i]+" ");35 }36 System.out.println(sb.toString());37 }38 }14.09 正則表達式的替換功能
public String replaceAll(String regex,String replacement):
使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串。
例:
String s = "sdfds123543ghdf655334gf";//String regex = "http://d"; //出現一次數字用*代替String regex = "http://d+"; //出現一次或多次數字用一個*代替String ss = s.replaceAll(regex, "*");System.out.println(ss);
運行結果:
sdfds*ghdf*gf
14.10 Pattern和Matcher的概述
類 Pattern正則表達式的編譯表示形式。
指定為字符串的正則表達式必須首先被編譯為此類的實例。然后,可將得到的模式用于創建 Matcher 對象,依照正則表達式,該對象可以與任意字符序列匹配。執行匹配所涉及的所有狀態都駐留在匹配器中,所以多個匹配器可以共享同一模式。
類 Matcher通過解釋 Pattern 對 character sequence 執行匹配操作的引擎。
典型的調用順序是
Pattern p = Pattern.compile("a*b");//將正則表達式編譯成模式對象
Matcher m = p.matcher("aaaaab");//通過模式對象得到匹配器對象,需要被匹配的字符串
boolean b = m.matches();//調用匹配器對象的功能
14.11 正則表達式的獲取功能
獲取字符串中由三個字符組成的單詞
1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3 public class Practice 4 { 5 public static void main(String[] args) 6 { 7 String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?"; 8 String regex = "http://b//w{3}//b"; 9 Pattern p = Pattern.compile(regex);10 Matcher m = p.matcher(s);11 while(m.find())12 {13 System.out.print(m.group()+" ");14 }15 }16 }運行結果:
jia jin yao xia wan gao
14.12 Math類概述和方法使用
Math 類包含用于執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。
成員方法:
1. public static int abs(int a):
返回 int 值的絕對值。
2. public static double ceil(double a):
返回最小的(最接近負無窮大)double 值,該值大于等于參數,并等于某個整數。向上取整
3. public static double floor(double a):
返回最大的(最接近正無窮大)double 值,該值小于等于參數,并等于某個整數。向下取整
4. public static int max(int a,int b):
返回兩個 int 值中較大的一個。
5. public static double pow(double a,double b):
返回第一個參數的第二個參數次冪的值。
6. public static double random():
返回帶正號的 double 值,該值大于等于 0.0 且小于 1.0。
7. public static int round(float a):
返回最接近參數的 int。
8. public static double sqrt(double a):
返回正確舍入的 double 值的正平方根。
例:
1 System.out.println("E:"+Math.E);//E:2.718281828459045 2 System.out.println("PI:"+Math.PI);//PI:3.141592653589793 3 System.out.println("abs:"+Math.abs(-10));//abs:10 4 System.out.println("ceil:"+Math.ceil(12.34));//ceil:13.0 5 System.out.println("ceil:"+Math.ceil(12.56));//ceil:13.0 6 System.out.println("floor:"+Math.floor(12.34));//floor:12.0 7 System.out.println("floor:"+Math.floor(12.56));//floor:12.0 8 System.out.println("pow:"+Math.pow(2, 3));//pow:8.0 9 System.out.println("random:"+Math.random());//random:0.875584197878383310 System.out.println("round:"+Math.round(12.34));//round:1211 System.out.println("round:"+Math.round(12.56));//round:1314.13 獲取任意范圍內的隨機數案例
1 public static int getRandom(int start,int end)2 {3 int num = (int)(Math.random()*(end-start)+1)+start;4 return num;5 }14.14 Random類的概述和方法使用
此類用于產生隨機數
如果用相同的種子創建兩個 Random 實例,則對每個實例進行相同的方法調用序列,它們將生成并返回相同的數字序列。
構造方法
public Random():
創建一個新的隨機數生成器。此構造方法將隨機數生成器的種子設置為某個值,該值與此構造方法的所有其他調用所用的值完全不同。默認的種子是當前時間的毫秒值。每次得到的數是不同的。
public Random(long seed):
使用單個 long 種子創建一個新的隨機數生成器。該種子是偽隨機數生成器的內部狀態的初始值,該生成器可通過方法 next(int) 維護。每次得到的數是相同的。
成員方法
public int nextInt():
返回下一個偽隨機數,它是此隨機數生成器的序列中均勻分布的 int 值。
public int nextInt(int n):
返回一個偽隨機數,它是取自此隨機數生成器序列的、在 0(包括)和指定值(不包括)之間均勻分布的 int 值。
14.15 System類中垃圾回收的方法gc()的講解
System 類包含一些有用的類字段和方法。它不能被實例化。
成員方法
public static void gc():
運行垃圾回收器。
執行System.gc()前,系統會自動調用finalize()方法清除對象占有的資源,通過super.finalize()方式可以實現從下到上的finalize()方法的調用,即先釋放自己的資源,再去釋放父類的資源。
14.16 System類中的exit()和currentTimeMillis()的講解
public static void exit(int status):
終止當前正在運行的 Java 虛擬機。參數用作狀態碼;根據慣例,非 0 的狀態碼表示異常終止。
public static long currentTimeMillis():
返回以毫秒為單位的當前時間。
14.17 System類中的arraycopy()的講解
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length):
從指定源數組中復制一個數組,復制從指定的位置開始,到目標數組的指定位置結束。
例:
1 int[] arr1 = {11,22,33,44,55};2 int[] arr2 = {6,7,8,9,10};3 System.arraycopy(arr1, 1, arr2, 2, 2);4 System.out.println(Arrays.toString(arr1));5 System.out.println(Arrays.toString(arr2));運行結果:
[11, 22, 33, 44, 55][6, 7, 22, 33, 10]
14.18 BigInteger的概述和構造方法
BigInteger類概述:可以讓超過Integer范圍內的數據進行運算
構造方法:
public BigInteger(String val):
將 BigInteger 的十進制字符串表示形式轉換為 BigInteger。
例:
System.out.println(Integer.MAX_VALUE);//2147483647
BigInteger bi = new BigInteger("2147483648");
System.out.println(bi);
14.19 BigInteger的加減乘除法的使用
成員方法
1. public BigInteger add(BigInteger val):返回其值為 (this + val) 的 BigInteger。
2. public BigInteger subtract(BigInteger val):返回其值為 (this - val) 的 BigInteger。
3. public BigInteger multiply(BigInteger val):返回其值為 (this * val) 的 BigInteger。
4. public BigInteger divide(BigInteger val):返回其值為 (this / val) 的 BigInteger。
5. public BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 后跟 (this % val) 的兩個 BigInteger 的數組。
例:
1 BigInteger bi1 = new BigInteger("100"); 2 BigInteger bi2 = new BigInteger("50"); 3 4 System.out.println("加法:"+bi1.add(bi2)); 5 System.out.println("減法:"+bi1.subtract(bi2)); 6 System.out.println("乘法:"+bi1.multiply(bi2)); 7 System.out.println("除法:"+bi1.divide(bi2)); 8 9 BigInteger[] bis = bi1.divideAndRemainder(bi2);10 System.out.println("商:"+bis[0]);11 System.out.println("余數:"+bis[1]);運行結果:
加法:150減法:50乘法:5000除法:2商:2余數:0
14.20 BigDecimal的引入和概述
由于在運算的時候,float類型和double很容易丟失精度。
例:
System.out.println(0.09 + 0.01);//0.09999999999999999System.out.println(1.0 - 0.32);//0.6799999999999999System.out.println(1.015 * 100);//101.49999999999999System.out.println(1.301 / 100);//0.013009999999999999
所以,為了能精確的表示、計算浮點數,Java提供了BigDecimal
BigDecimal類概述:不可變的、任意精度的有符號十進制數。
構造方法
public BigDecimal(String val):
將 BigDecimal 的字符串表示形式轉換為 BigDecimal。
14.21 BigDecimal的加減乘除法的使用
成員方法:
1. public BigDecimal add(BigDecimal augend)
返回一個 BigDecimal,其值為 (this + augend),其標度為 max(this.scale(), augend.scale())。
2. public BigDecimal subtract(BigDecimal subtrahend)
返回一個 BigDecimal,其值為 (this - subtrahend),其標度為 max(this.scale(), subtrahend.scale())。
3. public BigDecimal multiply(BigDecimal multiplicand)
返回一個 BigDecimal,其值為 (this × multiplicand),其標度為 (this.scale() + multiplicand.scale())。
4. public BigDecimal divide(BigDecimal divisor)
返回一個 BigDecimal,其值為 (this / divisor),其首選標度為 (this.scale() - divisor.scale());如果無法表示準確的商值(因為它有無窮的十進制擴展),則拋出 ArithmeticException。
5. public BigDecimal divide(BigDecimal divisor,int scale,RoundingMode roundingMode)
返回一個 BigDecimal,其值為 (this / divisor),其標度為指定標度。如果必須執行舍入,以生成具有指定標度的結果,則應用指定的舍入模式。
例:
1 BigDecimal bd1 = new BigDecimal("0.09"); 2 BigDecimal bd2 = new BigDecimal("0.01"); 3 System.out.println("加法:"+bd1.add(bd2)); 4 5 BigDecimal bd3 = new BigDecimal("1.0"); 6 BigDecimal bd4 = new BigDecimal("0.32"); 7 System.out.println("減法:"+bd3.subtract(bd4)); 8 9 BigDecimal bd5 = new BigDecimal("1.015");10 BigDecimal bd6 = new BigDecimal("100");11 System.out.println("乘法:"+bd5.multiply(bd6));12 13 BigDecimal bd7 = new BigDecimal("1.301");14 BigDecimal bd8 = new BigDecimal("100");15 System.out.println("除法:"+bd7.divide(bd8));16 17 18 System.out.println("除法:"+bd7.divide(bd8,3,BigDecimal.ROUND_HALF_UP));運行結果:
加法:0.10減法:0.68乘法:101.500除法:0.01301除法:0.013
14.22 Date的概述和構造方法
Date類概述:類 Date 表示特定的瞬間,精確到毫秒。
構造方法
public Date():
分配 Date 對象并初始化此對象,以表示分配它的時間(精確到毫秒)。
public Date(long date):
分配 Date 對象并初始化此對象,以表示自從標準基準時間(稱為“歷元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以來的指定毫秒數。
例:
1 Date d1 = new Date();2 System.out.println(d1);//Thu May 21 16:56:34 CST 20143 Date d2 = new Date(3600000);4 System.out.println(d2);//Thu Jan 01 09:00:00 CST 1970
14.23 Date類中日期和毫秒的相互轉換
成員方法
public long getTime():
返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。
public void setTime(long time):
設置此 Date 對象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的時間點。
例:
Date d = new Date();//獲取時間毫秒值System.out.println(d.getTime());1432198839578//設置時間d.setTime(1000);System.out.println(d);Thu Jan 01 08:00:01 CST 1970
Date得到毫秒值: 使用Date對象的getTime()方法
毫秒值得到Date: 1.構造方法2.使用Date對象的setTime()方法
14.24 DateFormat實現日期和字符串的相互轉換
DateFormat類概述:DateFormat 是日期/時間格式化子類的抽象類,它以與語言無關的方式格式化并解析日期或時間。
日期/時間格式化子類(如 SimpleDateFormat)允許進行格式化(也就是日期 -> 文本)、解析(文本-> 日期)和標準化
是抽象類,所以要使用其具體子類SimpleDateFormat
SimpleDateFormat構造方法:
public SimpleDateFormat():
用默認的模式和默認語言環境的日期格式符號構造 SimpleDateFormat。
public SimpleDateFormat(String pattern):
用給定的模式和默認語言環境的日期格式符號構造 SimpleDateFormat。
成員方法
public final String format(Date date):
將一個 Date 格式化為日期/時間字符串。
public Date parse(String source)throws ParseException:
從給定字符串的開始解析文本,以生成一個日期。該方法不使用給定字符串的整個文本。
例:
1 //創建日期對象 2 Date d = new Date(); 3 //創建格式化對象,默認格式 4 //SimpleDateFormat sdf = new SimpleDateFormat(); 5 //自定義格式 6 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 7 String str = sdf.format(d); 8 //默認格式的輸出 9 //System.out.println(str);//15-3-21 下午5:1110 //自定義格式的輸出11 System.out.println(str);//2015年03月21日 17:16:0112 13 14 15 String s = "2009-08-08 12:34:45";16 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");17 //字符串轉日期18 Date d2 = sdf2.parse(s);19 System.out.println(d2);//Sat Aug 08 12:34:45 CST 200914.25 日期工具類的編寫和測試案例
//測試類import java.text.ParseException;import java.util.Date;public class Practice { public static void main(String[] args) throws ParseException { Date d = new Date(); String s = DateUtil.dateToString(d, "yyyy-MM-dd HH:mm:ss"); System.out.println(s); Date d2 = DateUtil.stringToDate("2008-08-08", "yyyy-MM-dd"); System.out.println(d2); }} 1 //工具類 2 import java.text.ParseException; 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 public class DateUtil 7 { 8 private DateUtil(){} 9 10 public static String dateToString(Date d,String format)11 {12 SimpleDateFormat sdf = new SimpleDateFormat(format);13 String s = sdf.format(d);14 return s;15 }16 public static Date stringToDate(String s,String format) throws ParseException17 {18 SimpleDateFormat sdf = new SimpleDateFormat(format);19 Date d = sdf.parse(s);20 return d;21 }22 }14.26 計算你來到這個世界多少天案例
1 import java.text.ParseException; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 5 public class Practice 6 { 7 public static void main(String[] args) throws ParseException 8 { 9 String date = "1990-05-10";10 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");11 //將字符串轉為日期對象12 Date d = sdf.parse(date);13 //通過日期對象得到毫秒值14 long time1 = d.getTime();15 //獲得當前時間的毫秒值16 long time2 = System.currentTimeMillis();17 long time = time2 - time1;18 System.out.println(time/1000/60/60/24+"天");19 }20 }14.27 Calendar類的概述和獲取日歷字段的方法
Calendar 類是一個抽象類,它為特定瞬間與一組諸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日歷字段之間的轉換提供了一些方法,并為操作日歷字段(例如獲得下星期的日期)提供了一些方法。
成員方法:
1. public static Calendar getInstance():
使用默認時區和語言環境獲得一個日歷。返回的 Calendar 基于當前時間,使用了默認時區和默認語言環境。
2. public int get(int field):
返回給定日歷字段的值。
例:
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));//2015
14.28 Calendar類的add()和set()方法
1. public abstract void add(int field,int amount):
根據日歷的規則,為給定的日歷字段添加或減去指定的時間量。
2. public final void set(int year,int month,int date):
設置日歷字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。保留其他日歷字段以前的值。
例:
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -3);
System.out.println(c.get(Calendar.YEAR));//2012
14.29 獲取任意年份的2月份有多少天案例
1 import java.util.Calendar; 2 import java.util.Scanner; 3 4 public class Practice 5 { 6 public static void main(String[] args) 7 { 8 Scanner sc = new Scanner(System.in); 9 System.out.println("請輸入年份:");10 int year = sc.nextInt();11 12 Calendar c = Calendar.getInstance();13 //將時間定在任意一年的3月1日14 c.set(year, 2, 1);15 c.add(Calendar.DAY_OF_MONTH, -1);16 int day = c.get(Calendar.DAY_OF_MONTH);17 System.out.println(year+"年的二月有"+day+"天");18 19 }20 }運行結果:
請輸入年份:
2008
2008年的二月有29天
新聞熱點
疑難解答