Java_String_Arrays_Character_BigDecimal_Calendar_Math_System
生活随笔
收集整理的這篇文章主要介紹了
Java_String_Arrays_Character_BigDecimal_Calendar_Math_System
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.String
package cn.itcast_01; /* * Scanner:用于接收鍵盤錄入數據。 * * 前面的時候: * A:導包 * B:創建對象 * C:調用方法 * * System類下有一個靜態的字段: * public static final InputStream in; 標準的輸入流,對應著鍵盤錄入。 * * InputStream is = System.in; //靜態的類成員變量in system類直接調用 * * class Demo { * public static final int x = 10; * public static final Student s = new Student(); * } * int y = Demo.x; * Student s = Demo.s; * * * 構造方法: * Scanner(InputStream source) */ import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.println("x:" + x); } } ====================================================== package cn.itcast_02; import java.util.Scanner; /* * 基本格式: * public boolean hasNextXxx():判斷是否是某種類型的元素 * public Xxx nextXxx():獲取該元素 * * 舉例:用int類型的方法舉例 * public boolean hasNextInt() * public int nextInt() * * 注意: * InputMismatchException:輸入的和你想要的不匹配 */ public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); // 獲取數據 if (sc.hasNextInt()) { int x = sc.nextInt(); System.out.println("x:" + x); } else { System.out.println("你輸入的數據有誤"); } } } ================================================================== package cn.itcast_03; import java.util.Scanner; /* * 常用的兩個方法: * public int nextInt():獲取一個int類型的值 * public String nextLine():獲取一個String類型的值 * * 出現問題了: * 先獲取一個數值,在獲取一個字符串,會出現問題。 * 主要原因:就是那個換行符號的問題。 * 如何解決呢? * A:先獲取一個數值后,在創建一個新的鍵盤錄入對象獲取字符串。 * B:把所有的數據都先按照字符串獲取,然后要什么,你就對應的轉換為什么。 */ public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); // 獲取兩個int類型的值 // int a = sc.nextInt(); // int b = sc.nextInt(); // System.out.println("a:" + a + ",b:" + b); // System.out.println("-------------------"); // 獲取兩個String類型的值 // String s1 = sc.nextLine(); // String s2 = sc.nextLine(); // System.out.println("s1:" + s1 + ",s2:" + s2); // System.out.println("-------------------"); // 先獲取一個字符串,在獲取一個int值 // String s1 = sc.nextLine(); // int b = sc.nextInt(); // System.out.println("s1:" + s1 + ",b:" + b); // System.out.println("-------------------"); // 先獲取一個int值,在獲取一個字符串 // int a = sc.nextInt(); // String s2 = sc.nextLine(); // System.out.println("a:" + a + ",s2:" + s2); // System.out.println("-------------------"); int a = sc.nextInt(); Scanner sc2 = new Scanner(System.in); String s = sc2.nextLine(); System.out.println("a:" + a + ",s:" + s); } } =========================================================================== package cn.itcast_01; /* * 字符串:就是由多個字符組成的一串數據。也可以看成是一個字符數組。 * 通過查看API,我們可以知道 * A:字符串字面值"abc"也可以看成是一個字符串對象。 * B:字符串是常量,一旦被賦值,就不能被改變。 * * 構造方法: * public String():空構造 * public String(byte[] bytes):把字節數組轉成字符串 * public String(byte[] bytes,int index,int length):把字節數組的一部分轉成字符串 * public String(char[] value):把字符數組轉成字符串 * public String(char[] value,int index,int count):把字符數組的一部分轉成字符串 * public String(String original):把字符串常量值轉成字符串 * * 字符串的方法: * public int length():返回此字符串的長度。 */ public class StringDemo { public static void main(String[] args) { // public String():空構造 String s1 = new String(); System.out.println("s1:" + s1); System.out.println("s1.length():" + s1.length()); System.out.println("--------------------------"); // public String(byte[] bytes):把字節數組轉成字符串b byte[] bys = { 97, 98, 99, 100, 101 }; String s2 = new String(bys); System.out.println("s2:" + s2); System.out.println("s2.length():" + s2.length()); System.out.println("--------------------------"); // public String(byte[] bytes,int index,int length):把字節數組的一部分轉成字符串 // 我想得到字符串"bcd" String s3 = new String(bys, 1, 3); System.out.println("s3:" + s3); System.out.println("s3.length():" + s3.length()); Systebbm.out.println("--------------------------"); // public String(char[] value):把字符數組轉成字符串 char[] chs = { 'a', 'b', 'c', 'd', 'e', '愛', '林', '親' }; String s4 = new String(chs); System.out.println("s4:" + s4); System.out.println("s4.length():" + s4.length()); System.out.println("--------------------------"); // public String(char[] value,int index,int count):把字符數組的一部分轉成字符串 String s5 = new String(chs, 2, 4); System.out.println("s5:" + s5); System.out.println("s5.length():" + s5.length()); System.out.println("--------------------------"); //public String(String original):把字符串常量值轉成字符串 String s6 = new String("abcde"); System.out.println("s6:" + s6); System.out.println("s6.length():" + s6.length()); System.out.println("--------------------------"); //字符串字面值"abc"也可以看成是一個字符串對象。 String s7 = "abcde"; System.out.println("s7:"+s7); System.out.println("s7.length():"+s7.length()); } } ====================================================================== package cn.itcast_02; /* * 字符串的特點:一旦被賦值,就不能改變。 */ public class StringDemo { public static void main(String[] args) { String s = "hello"; s += "world"; System.out.println("s:" + s); // helloworld } } ============================================================= package cn.itcast_02; /* * String s = new String(“hello”)和String s = “hello”;的區別? * 有。前者會創建2個對象,后者創建1個對象。 * * ==:比較引用類型比較的是地址值是否相同 * equals:比較引用類型默認也是比較地址值是否相同,而String類重寫了equals()方法,比較的是內容是否相同。 */ public class StringDemo2 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = "hello"; System.out.println(s1 == s2);// false System.out.println(s1.equals(s2));// true } } ============================================================= package cn.itcast_02; /* * 看程序寫結果 */ public class StringDemo3 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1 == s2);// false System.out.println(s1.equals(s2));// true String s3 = new String("hello"); String s4 = "hello"; System.out.println(s3 == s4);// false System.out.println(s3.equals(s4));// true String s5 = "hello"; String s6 = "hello"; System.out.println(s5 == s6);// true System.out.println(s5.equals(s6));// true } } ===========================================================================package cn.itcast_02; /* * 看程序寫結果 * 字符串如果是變量相加,先開空間,在拼接。 * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否則,就創建。 */ public class StringDemo4 { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; System.out.println(s3 == s1 + s2);// false System.out.println(s3.equals((s1 + s2)));// true System.out.println(s3 == "hello" + "world");// false 這個我們錯了,應該是true System.out.println(s3.equals("hello" + "world"));// true // 通過反編譯看源碼,我們知道這里已經做好了處理。 // System.out.println(s3 == "helloworld"); // System.out.println(s3.equals("helloworld")); } } ====================================================== package cn.itcast_03; import java.util.Scanner; /* * 這時猜數字小游戲的代碼 */ public class GuessNumberGame { private GuessNumberGame() { } public static void start() { // 產生一個隨機數 int number = (int) (Math.random() * 100) + 1; while (true) { // 鍵盤錄入數據 Scanner sc = new Scanner(System.in); System.out.println("請輸入你要猜的數據(1-100):"); int guessNumber = sc.nextInt(); // 判斷 if (guessNumber > number) { System.out.println("你猜的數據" + guessNumber + "大了"); } else if (guessNumber < number) { System.out.println("你猜的數據" + guessNumber + "小了"); } else { System.out.println("恭喜你,猜中了"); break; } } } } ===========================================================================package cn.itcast_03; /* * String類的判斷功能: * boolean equals(Object obj):比較字符串的內容是否相同,區分大小寫 * boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 * boolean contains(String str):判斷大字符串中是否包含小字符串 * boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭 * boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾 * boolean isEmpty():判斷字符串是否為空。 * * 注意: * 字符串內容為空和字符串對象為空。 * String s = ""; * String s = null; */ public class StringDemo { public static void main(String[] args) { // 創建字符串對象 String s1 = "helloworld"; String s2 = "helloworld"; String s3 = "HelloWorld"; // boolean equals(Object obj):比較字符串的內容是否相同,區分大小寫 System.out.println("equals:" + s1.equals(s2)); System.out.println("equals:" + s1.equals(s3)); System.out.println("-----------------------"); // boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 System.out.println("equals:" + s1.equalsIgnoreCase(s2)); System.out.println("equals:" + s1.equalsIgnoreCase(s3)); System.out.println("-----------------------"); // boolean contains(String str):判斷大字符串中是否包含小字符串 System.out.println("contains:" + s1.contains("hello")); System.out.println("contains:" + s1.contains("hw"));//要連在一起才行 System.out.println("-----------------------"); // boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭 System.out.println("startsWith:" + s1.startsWith("h")); System.out.println("startsWith:" + s1.startsWith("hello")); System.out.println("startsWith:" + s1.startsWith("world")); System.out.println("-----------------------"); // 練習:boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾這個自己玩 // boolean isEmpty():判斷字符串是否為空。 System.out.println("isEmpty:" + s1.isEmpty()); String s4 = ""; String s5 = null; System.out.println("isEmpty:" + s4.isEmpty()); // NullPointerException // s5對象都不存在,所以不能調用方法,空指針異常,見的非常多 System.out.println("isEmpty:" + s5.isEmpty()); } } =========================================================== package cn.itcast_03; import java.util.Scanner; /* * 模擬登錄,給三次機會,并提示還有幾次。 * * 分析: * A:定義用戶名和密碼。已存在的。 * B:鍵盤錄入用戶名和密碼。 * C:比較用戶名和密碼。 * 如果都相同,則登錄成功 * 如果有一個不同,則登錄失敗 * D:給三次機會,用循環改進,最好用for循環。 */ public class StringTest { public static void main(String[] args) { // 定義用戶名和密碼。已存在的。 String username = "admin"; String password = "admin"; // 給三次機會,用循環改進,最好用for循環。 for (int x = 0; x < 3; x++) { // x=0,1,2 // 鍵盤錄入用戶名和密碼。 Scanner sc = new Scanner(System.in); System.out.println("請輸入用戶名:"); String name = sc.nextLine(); System.out.println("請輸入密碼:"); String pwd = sc.nextLine(); // 比較用戶名和密碼。 if (name.equals(username) && pwd.equals(password)) { // 如果都相同,則登錄成功 System.out.println("登錄成功"); break; } else { // 如果有一個不同,則登錄失敗 // 2,1,0 // 如果是第0次,應該換一種提示 if ((2 - x) == 0) { System.out.println("帳號被鎖定,請與班長聯系"); } else { System.out.println("登錄失敗,你還有" + (2 - x) + "次機會"); } } } } } =========================================================================== package cn.itcast_03; import java.util.Scanner; /* * 模擬登錄,給三次機會,并提示還有幾次。如果登錄成功,就可以玩猜數字小游戲了。 * * 分析: * A:定義用戶名和密碼。已存在的。 * B:鍵盤錄入用戶名和密碼。 * C:比較用戶名和密碼。 * 如果都相同,則登錄成功 * 如果有一個不同,則登錄失敗 * D:給三次機會,用循環改進,最好用for循環。 */ public class StringTest2 { public static void main(String[] args) { // 定義用戶名和密碼。已存在的。 String username = "admin"; String password = "admin"; // 給三次機會,用循環改進,最好用for循環。 for (int x = 0; x < 3; x++) { // x=0,1,2 // 鍵盤錄入用戶名和密碼。 Scanner sc = new Scanner(System.in); System.out.println("請輸入用戶名:"); String name = sc.nextLine(); System.out.println("請輸入密碼:"); String pwd = sc.nextLine(); // 比較用戶名和密碼。 if (name.equals(username) && pwd.equals(password)) { // 如果都相同,則登錄成功 System.out.println("登錄成功,開始玩游戲"); //猜數字游戲 GuessNumberGame.start(); break; } else { // 如果有一個不同,則登錄失敗 // 2,1,0 // 如果是第0次,應該換一種提示 if ((2 - x) == 0) { System.out.println("帳號被鎖定,請與班長聯系"); } else { System.out.println("登錄失敗,你還有" + (2 - x) + "次機會"); } } } } } ============================================= Java線程中run和start方法的區別 Thread類中run()和start()方法的區別如下: run()方法:在本線程內調用該Runnable對象的run()方法,可以重復多次調用; start()方法:啟動一個線程,調用該Runnable對象的run()方法,不能多次啟動一個線程; ============================================================== package cn.itcast_04; /* * String類的獲取功能 * int length():獲取字符串的長度。 * char charAt(int index):獲取指定索引位置的字符 * int indexOf(int ch):返回指定字符在此字符串中第一次出現處的索引。 * 為什么這里是int類型,而不是char類型? * 原因是:'a'和97其實都可以代表'a' * int indexOf(String str):返回指定字符串在此字符串中第一次出現處的索引。 * int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現處的索引。 * int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現處的索引。 * String substring(int start):從指定位置開始截取字符串,默認到末尾。 * String substring(int start,int end):從指定位置開始到指定位置結束截取字符串。 */ public class StringDemo { public static void main(String[] args) { // 定義一個字符串對象 String s = "helloworld"; // int length():獲取字符串的長度。 System.out.println("s.length:" + s.length()); System.out.println("----------------------"); // char charAt(int index):獲取指定索引位置的字符 System.out.println("charAt:" + s.charAt(7)); System.out.println("----------------------"); // int indexOf(int ch):返回指定字符在此字符串中第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf('l')); System.out.println("----------------------"); // int indexOf(String str):返回指定字符串在此字符串中第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf("owo")); System.out.println("----------------------"); // int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現處的索引。 System.out.println("indexOf:" + s.indexOf('l', 4)); System.out.println("indexOf:" + s.indexOf('k', 4)); // -1 System.out.println("indexOf:" + s.indexOf('l', 40)); // -1 System.out.println("----------------------"); // 自己練習:int indexOf(String str,int // fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現處的索引。 // String substring(int start):從指定位置開始截取字符串,默認到末尾。包含start這個索引 System.out.println("substring:" + s.substring(5)); System.out.println("substring:" + s.substring(0)); System.out.println("----------------------"); // String substring(int start,int // end):從指定位置開始到指定位置結束截取字符串。包括start索引但是不包end索引 System.out.println("substring:" + s.substring(3, 8)); System.out.println("substring:" + s.substring(0, s.length())); } } s.length:10 ---------------------- charAt:r ---------------------- indexOf:2 ---------------------- indexOf:4 ---------------------- indexOf:8 indexOf:-1 indexOf:-1 ---------------------- substring:world substring:helloworld ---------------------- substring:lowor substring:helloworld =================================================== package cn.itcast_04; /* * 需求:遍歷獲取字符串中的每一個字符 * * 分析: * A:如何能夠拿到每一個字符呢? * char charAt(int index) * B:我怎么知道字符到底有多少個呢? * int length() */ public class StringTest { public static void main(String[] args) { // 定義字符串 String s = "helloworld"; // 原始版本 // System.out.println(s.charAt(0)); // System.out.println(s.charAt(1)); // System.out.println(s.charAt(2)); // System.out.println(s.charAt(3)); // System.out.println(s.charAt(4)); // System.out.println(s.charAt(5)); // System.out.println(s.charAt(6)); // System.out.println(s.charAt(7)); // System.out.println(s.charAt(8)); // System.out.println(s.charAt(9)); // 只需要我們從0取到9 // for (int x = 0; x < 10; x++) { // System.out.println(s.charAt(x)); // } // 如果長度特別長,我不可能去數,所以我們要用長度功能 for (int x = 0; x < s.length(); x++) { // char ch = s.charAt(x); // System.out.println(ch); // 僅僅是輸出,我就直接輸出了 System.out.println(s.charAt(x)); } } } ============================================= package cn.itcast_04; /* * 需求:統計一個字符串中大寫字母字符,小寫字母字符,數字字符出現的次數。(不考慮其他字符) * 舉例: * "Hello123World" * 結果: * 大寫字符:2個 * 小寫字符:8個 * 數字字符:3個 * * 分析: * 前提:字符串要存在 * A:定義三個統計變量 * bigCount=0 * smallCount=0 * numberCount=0 * B:遍歷字符串,得到每一個字符。 * length()和charAt()結合 * C:判斷該字符到底是屬于那種類型的 * 大:bigCount++ * 小:smallCount++ * 數字:numberCount++ * * 這道題目的難點就是如何判斷某個字符是大的,還是小的,還是數字的。 * ASCII碼表: * 0 48 * A 65 * a 97 * 雖然,我們按照數字的這種比較是可以的,但是想多了,有比這還簡單的 * char ch = s.charAt(x); * * if(ch>='0' && ch<='9') numberCount++ * if(ch>='a' && ch<='z') smallCount++ * if(ch>='A' && ch<='Z') bigCount++ * D:輸出結果。 * * 練習:把給定字符串的方式,改進為鍵盤錄入字符串的方式。 */ public class StringTest2 { public static void main(String[] args) { //定義一個字符串 String s = "Hello123World"; //定義三個統計變量 int bigCount = 0; int smallCount = 0; int numberCount = 0; //遍歷字符串,得到每一個字符。 for(int x=0; x<s.length(); x++){ char ch = s.charAt(x); //判斷該字符到底是屬于那種類型的 if(ch>='a' && ch<='z'){ smallCount++; }else if(ch>='A' && ch<='Z'){ bigCount++; }else if(ch>='0' && ch<='9'){ numberCount++; } } //輸出結果。 System.out.println("大寫字母"+bigCount+"個"); System.out.println("小寫字母"+smallCount+"個"); System.out.println("數字"+numberCount+"個"); } } =========================================== package cn.itcast_05; /* * String的轉換功能: * byte[] getBytes():把字符串轉換為字節數組。 * char[] toCharArray():把字符串轉換為字符數組。 * static String valueOf(char[] chs):把字符數組轉成字符串。 * static String valueOf(int i):把int類型的數據轉成字符串。 * 注意:String類的valueOf方法可以把任意類型的數據轉成字符串。 * String toLowerCase():把字符串轉成小寫。 * String toUpperCase():把字符串轉成大寫。 * String concat(String str):把字符串拼接。 */ public class StringDemo { public static void main(String[] args) { // 定義一個字符串對象 String s = "JavaSE"; // byte[] getBytes():把字符串轉換為字節數組。 byte[] bys = s.getBytes(); for (int x = 0; x < bys.length; x++) { System.out.println(bys[x]); } System.out.println("----------------"); // char[] toCharArray():把字符串轉換為字符數組。 char[] chs = s.toCharArray(); for (int x = 0; x < chs.length; x++) { System.out.println(chs[x]); } System.out.println("----------------"); // static String valueOf(char[] chs):把字符數組轉成字符串。 String ss = String.valueOf(chs); System.out.println(ss); System.out.println("----------------"); // static String valueOf(int i):把int類型的數據轉成字符串。 int i = 100; String sss = String.valueOf(i); System.out.println(sss); System.out.println("----------------"); // String toLowerCase():把字符串轉成小寫。 System.out.println("toLowerCase:" + s.toLowerCase()); System.out.println("s:" + s); // System.out.println("----------------"); // String toUpperCase():把字符串轉成大寫。 System.out.println("toUpperCase:" + s.toUpperCase()); System.out.println("----------------"); // String concat(String str):把字符串拼接。 String s1 = "hello"; String s2 = "world"; String s3 = s1 + s2; String s4 = s1.concat(s2); System.out.println("s3:"+s3); System.out.println("s4:"+s4); } } 74 97 118 97 83 69 ---------------- J a v a S E ---------------- JavaSE ---------------- 100 ---------------- toLowerCase:javase s:JavaSE toUpperCase:JAVASE ---------------- s3:helloworld s4:helloworld ================================== package cn.itcast_06; public class StringTest1 { public static void main(String[] args) { String s = "helloWORLD"; String s1 = s.substring(0,1); String s2 = s.substring(1); String s3 = s1.toUpperCase(); String s4 = s2.toLowerCase(); String s5 = s3.concat(s4); System.out.println(s5); String result = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase()); System.out.println(result); } } ===========================================================================package cn.itcast_06; /* * String類的其他功能: * * 替換功能: * String replace(char old,char new) * String replace(String old,String new) * * 去除字符串兩空格 * String trim() * * 按字典順序比較兩個字符串 * int compareTo(String str) * int compareToIgnoreCase(String str) */ public class StringDemo { public static void main(String[] args) { // 替換功能 String s1 = "helloworld"; String s2 = s1.replace('l', 'k'); String s3 = s1.replace("owo", "ak47"); System.out.println("s1:" + s1); System.out.println("s2:" + s2); System.out.println("s3:" + s3); System.out.println("---------------"); // 去除字符串兩空格 String s4 = " hello world "; String s5 = s4.trim(); System.out.println("s4:" + s4 + "---"); System.out.println("s5:" + s5 + "---"); // 按字典順序比較兩個字符串 String s6 = "hello"; String s7 = "hello"; String s8 = "abc"; String s9 = "xyz"; System.out.println(s6.compareTo(s7));// 0 System.out.println(s6.compareTo(s8));// 7 System.out.println(s6.compareTo(s9));// -16 } } ======================================================= package cn.itcast_06; /* * 如果我們看到問題了,看怎么辦呢? * 看源碼。 */ public class StringTest { public static void main(String[] args) { String s1 = "hello"; String s2 = "hel"; System.out.println(s1.compareTo(s2)); // 2 } } ========================================================== private final char value[]; 字符串會自動轉換為一個字符數組。 public int compareTo(String anotherString) { //this -- s1 -- "hello" //anotherString -- s2 -- "hel" int len1 = value.length; //this.value.length--s1.toCharArray().length--5 int len2 = anotherString.value.length;//s2.value.length -- s2.toCharArray().length--3 int lim = Math.min(len1, len2); //Math.min(5,3); -- lim=3; char v1[] = value; //s1.toCharArray() char v2[] = anotherString.value; //char v1[] = {'h','e','l','l','o'}; //char v2[] = {'h','e','l'}; int k = 0; while (k < lim) { char c1 = v1[k]; //c1='h','e','l' char c2 = v2[k]; //c2='h','e','l' if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; //5-3=2;最后長度相減去、 } String s1 = "hello"; String s2 = "hel"; System.out.println(s1.compareTo(s2)); // 2 ===================================================================== package cn.itcast_07; /* * 需求:把數組中的數據按照指定個格式拼接成一個字符串 * 舉例: * int[] arr = {1,2,3}; * 輸出結果: * "[1, 2, 3]" * 分析: * A:定義一個字符串對象,只不過內容為空 * B:先把字符串拼接一個"[" * C:遍歷int數組,得到每一個元素 * D:先判斷該元素是否為最后一個 * 是:就直接拼接元素和"]" * 不是:就拼接元素和逗號以及空格 * E:輸出拼接后的字符串 */ public class StringTest { public static void main(String[] args) { // 前提是數組已經存在 int[] arr = { 1, 2, 3 }; // 定義一個字符串對象,只不過內容為空 String s = ""; // 先把字符串拼接一個"[" s += "["; // 遍歷int數組,得到每一個元素 for (int x = 0; x < arr.length; x++) { // 先判斷該元素是否為最后一個 if (x == arr.length - 1) { // 就直接拼接元素和"]" s += arr[x]; s += "]"; } else { // 就拼接元素和逗號以及空格 s += arr[x]; s += ", "; } } // 輸出拼接后的字符串 System.out.println("最終的字符串是:" + s); } } =========================================================================== package cn.itcast_07; /* * 需求:把數組中的數據按照指定個格式拼接成一個字符串 * 舉例: * int[] arr = {1,2,3}; * 輸出結果: * "[1, 2, 3]" * 分析: * A:定義一個字符串對象,只不過內容為空 * B:先把字符串拼接一個"[" * C:遍歷int數組,得到每一個元素 * D:先判斷該元素是否為最后一個 * 是:就直接拼接元素和"]" * 不是:就拼接元素和逗號以及空格 * E:輸出拼接后的字符串 * * 把代碼用功能實現。 */ public class StringTest2 { public static void main(String[] args) { // 前提是數組已經存在 int[] arr = { 1, 2, 3 }; // 寫一個功能,實現結果 String result = arrayToString(arr); System.out.println("最終結果是:" + result); } /* * 兩個明確: 返回值類型:String 參數列表:int[] arr */ public static String arrayToString(int[] arr) { // 定義一個字符串 String s = ""; // 先把字符串拼接一個"[" s += "["; // 遍歷int數組,得到每一個元素 for (int x = 0; x < arr.length; x++) { // 先判斷該元素是否為最后一個 if (x == arr.length - 1) { // 就直接拼接元素和"]" s += arr[x]; s += "]"; } else { // 就拼接元素和逗號以及空格 s += arr[x]; s += ", "; } } return s; } } ================================== package cn.itcast_07; import java.util.Scanner; /* * 字符串反轉 * 舉例:鍵盤錄入”abc” * 輸出結果:”cba” * * 分析: * A:鍵盤錄入一個字符串 * B:定義一個新字符串 * C:倒著遍歷字符串,得到每一個字符 * a:length()和charAt()結合 * b:把字符串轉成字符數組 * D:用新字符串把每一個字符拼接起來 * E:輸出新串 */ public class StringTest3 { public static void main(String[] args) { // 鍵盤錄入一個字符串 Scanner sc = new Scanner(System.in); System.out.println("請輸入一個字符串:"); String line = sc.nextLine(); /* // 定義一個新字符串 String result = ""; // 把字符串轉成字符數組 char[] chs = line.toCharArray(); // 倒著遍歷字符串,得到每一個字符 for (int x = chs.length - 1; x >= 0; x--) { // 用新字符串把每一個字符拼接起來 result += chs[x]; } // 輸出新串 System.out.println("反轉后的結果是:" + result); */ // 改進為功能實現 String s = myReverse(line); System.out.println("實現功能后的結果是:" + s); } /* * 兩個明確: 返回值類型:String 參數列表:String */ public static String myReverse(String s) { // 定義一個新字符串 String result = ""; // 把字符串轉成字符數組 char[] chs = s.toCharArray(); // 倒著遍歷字符串,得到每一個字符 for (int x = chs.length - 1; x >= 0; x--) { // 用新字符串把每一個字符拼接起來 result += chs[x]; } return result; } } ======================================================= package cn.itcast_07; /* * 統計大串中小串出現的次數 * 舉例: * 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun" * 結果: * java出現了5次 * * 分析: * 前提:是已經知道了大串和小串。 * * A:定義一個統計變量,初始化值是0 * B:先在大串中查找一次小串第一次出現的位置 * a:索引是-1,說明不存在了,就返回統計變量 * b:索引不是-1, 說明存在,統計變量++ * C:把剛才的索引+小串的長度作為開始位置截取上一次的大串,返回一個新的字符串,并把該字符串的值重新賦值給大串 * D:回到B */ public class StringTest4 { public static void main(String[] args) { // 定義大串 String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"; // 定義小串 String minString = "java"; // 寫功能實現 int count = getCount(maxString, minString); System.out.println("Java在大串中出現了:" + count + "次"); } /* * 兩個明確: 返回值類型:int 參數列表:兩個字符串 */ public static int getCount(String maxString, String minString) { // 定義一個統計變量,初始化值是0 int count = 0; // 先在大串中查找一次小串第一次出現的位置 int index = maxString.indexOf(minString); // 索引不是-1,說明存在,統計變量++ while (index != -1) { count++; // 把剛才的索引+小串的長度作為開始位置截取上一次的大串,返回一個新的字符串,并把該字符串的值重新賦值給大串 int startIndex = index + minString.length(); maxString = maxString.substring(startIndex); // 繼續查 index = maxString.indexOf(minString); } return count; } } 2.Arrays Character StringBuffer package cn.itcast_01; /* * 數組排序之冒泡排序: * 相鄰元素兩兩比較,大的往后放,第一次完畢,最大值出現在了最大索引處 */ public class ArrayDemo { public static void main(String[] args) { // 定義一個數組 int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:"); printArray(arr); /* // 第一次比較 // arr.length - 1是為了防止數據越界 // arr.length - 1 - 0是為了減少比較的次數 for (int x = 0; x < arr.length - 1 - 0; x++) { if (arr[x] > arr[x + 1]) { int temp = arr[x]; arr[x] = arr[x + 1]; arr[x + 1] = temp; } } System.out.println("第一次比較后:"); printArray(arr); // 第二次比較 // arr.length - 1是為了防止數據越界 // arr.length - 1 - 1是為了減少比較的次數 for (int x = 0; x < arr.length - 1 - 1; x++) { if (arr[x] > arr[x + 1]) { int temp = arr[x]; arr[x] = arr[x + 1]; arr[x + 1] = temp; } } System.out.println("第二次比較后:"); printArray(arr); // 第三次比較 // arr.length - 1是為了防止數據越界 // arr.length - 1 - 2是為了減少比較的次數 for (int x = 0; x < arr.length - 1 - 2; x++) { if (arr[x] > arr[x + 1]) { int temp = arr[x]; arr[x] = arr[x + 1]; arr[x + 1] = temp; } } System.out.println("第三次比較后:"); printArray(arr); // 第四次比較 // arr.length - 1是為了防止數據越界 // arr.length - 1 - 3是為了減少比較的次數 for (int x = 0; x < arr.length - 1 - 3; x++) { if (arr[x] > arr[x + 1]) { int temp = arr[x]; arr[x] = arr[x + 1]; arr[x + 1] = temp; } } System.out.println("第四次比較后:"); printArray(arr); */ // 既然聽懂了,那么上面的代碼就是排序代碼 // 而上面的代碼重復度太高了,所以用循環改進 // for (int y = 0; y < 4; y++) { // for (int x = 0; x < arr.length - 1 - y; x++) { // if (arr[x] > arr[x + 1]) { // int temp = arr[x]; // arr[x] = arr[x + 1]; // arr[x + 1] = temp; // } // } // } /* // 由于我們知道比較的次數是數組長度-1次,所以改進最終版程序 for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } System.out.println("排序后:"); printArray(arr); */ //由于我可能有多個數組要排序,所以我要寫成方法 bubbleSort(arr); System.out.println("排序后:"); printArray(arr); } //冒泡排序代碼 public static void bubbleSort(int[] arr){ for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } } // 遍歷功能 public static void printArray(int[] arr) { System.out.print("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { System.out.print(arr[x]); } else { System.out.print(arr[x] + ", "); } } System.out.println("]"); } } ======================================================== package cn.itcast_02; /* * 數組排序之選擇排序: * 從0索引開始,依次和后面元素比較,小的往前放,第一次完畢,最小值出現在了最小索引處 */ public class ArrayDemo { public static void main(String[] args) { // 定義一個數組 int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:"); printArray(arr); /* // 第一次 int x = 0; for (int y = x + 1; y < arr.length; y++) { if (arr[y] < arr[x]) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } System.out.println("第一次比較后:"); printArray(arr); // 第二次 x = 1; for (int y = x + 1; y < arr.length; y++) { if (arr[y] < arr[x]) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } System.out.println("第二次比較后:"); printArray(arr); // 第三次 x = 2; for (int y = x + 1; y < arr.length; y++) { if (arr[y] < arr[x]) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } System.out.println("第三次比較后:"); printArray(arr); // 第四次 x = 3; for (int y = x + 1; y < arr.length; y++) { if (arr[y] < arr[x]) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } System.out.println("第四次比較后:"); printArray(arr); */ /* //通過觀察發現代碼的重復度太高,所以用循環改進 for(int x=0; x<arr.length-1; x++){ for(int y=x+1; y<arr.length; y++){ if(arr[y] <arr[x]){ int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } } System.out.println("排序后:"); printArray(arr); */ //用方法改進 selectSort(arr); System.out.println("排序后:"); printArray(arr); } public static void selectSort(int[] arr){ for(int x=0; x<arr.length-1; x++){ for(int y=x+1; y<arr.length; y++){ if(arr[y] <arr[x]){ int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } } } } // 遍歷功能 public static void printArray(int[] arr) { System.out.print("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { System.out.print(arr[x]); } else { System.out.print(arr[x] + ", "); } } System.out.println("]"); } } =========================================================== package cn.itcast_03; /* * 把字符串中的字符進行排序。 * 舉例:"dacgebf" * 結果:"abcdefg" * * 分析: * A:定義一個字符串 * B:把字符串轉換為字符數組toCharArray() * C:把字符數組進行排序 * D:把排序后的字符數組轉成字符串valueOf(chs) * E:輸出最后的字符串 */ public class ArrayTest { public static void main(String[] args) { // 定義一個字符串 String s = "dacgebf"; // 把字符串轉換為字符數組 char[] chs = s.toCharArray(); // 把字符數組進行排序 bubbleSort(chs); //把排序后的字符數組轉成字符串 String result = String.valueOf(chs); //輸出最后的字符串 System.out.println("result:"+result); } // 冒泡排序 public static void bubbleSort(char[] chs) { for (int x = 0; x < chs.length - 1; x++) { for (int y = 0; y < chs.length - 1 - x; y++) { if (chs[y] > chs[y + 1]) { char temp = chs[y]; chs[y] = chs[y + 1]; chs[y + 1] = temp; } } } } } ============================================= package cn.itcast_04; /* * 查找: * 基本查找:數組元素無序(從頭找到尾) * 二分查找(折半查找):數組元素有序 * * 分析: * A:定義最大索引,最小索引 * B:計算出中間索引 * C:拿中間索引的值和要查找的值進行比較 * 相等:就返回當前的中間索引 * 不相等: * 大 左邊找 * 小 右邊找 * D:重新計算出中間索引 * 大 左邊找 * max = mid - 1; * 小 右邊找 * min = mid + 1; * E:回到B */ public class ArrayDemo { public static void main(String[] args) { //定義一個數組 int[] arr = {11,22,33,44,55,66,77}; //寫功能實現 int index = getIndex(arr, 33); System.out.println("index:"+index); //假如這個元素不存在后有什么現象呢? index = getIndex(arr, 333); System.out.println("index:"+index); } /* * 兩個明確: * 返回值類型:int * 參數列表:int[] arr,int value */ public static int getIndex(int[] arr,int value){ //定義最大索引,最小索引 int max = arr.length -1; int min = 0; //計算出中間索引 int mid = (max +min)/2; //拿中間索引的值和要查找的值進行比較 while(arr[mid] != value){ if(arr[mid]>value){ max = mid - 1; }else if(arr[mid]<value){ min = mid + 1; } //加入判斷 if(min > max){ return -1; } mid = (max +min)/2; } return mid; } } ===========================================================================package cn.itcast_04; /* * 注意:下面這種做法是有問題的。 * 因為數組本身是無序的,所以這種情況下的查找不能使用二分查找。 * 所以你先排序了,但是你排序的時候已經改變了我最原始的元素索引。 */ public class ArrayDemo2 { public static void main(String[] args) { // 定義數組 int[] arr = { 24, 69, 80, 57, 13 }; // 先排序 bubbleSort(arr); // 后查找 int index = getIndex(arr, 80); System.out.println("index:" + index); } // 冒泡排序代碼 public static void bubbleSort(int[] arr) { for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } } // 二分查找 public static int getIndex(int[] arr, int value) { // 定義最大索引,最小索引 int max = arr.length - 1; int min = 0; // 計算出中間索引 int mid = (max + min) / 2; // 拿中間索引的值和要查找的值進行比較 while (arr[mid] != value) { if (arr[mid] > value) { max = mid - 1; } else if (arr[mid] < value) { min = mid + 1; } // 加入判斷 if (min > max) { return -1; } mid = (max + min) / 2; } return mid; } } ======================================================== package cn.itcast_05; import java.util.Arrays; /* * Arrays:針對數組進行操作的工具類。比如說排序和查找。 * 1:public static String toString(int[] a) 把數組轉成字符串 * 2:public static void sort(int[] a) 對數組進行排序 * 3:public static int binarySearch(int[] a,int key) 二分查找 */ public class ArraysDemo { public static void main(String[] args) { // 定義一個數組 int[] arr = { 24, 69, 80, 57, 13 }; // public static String toString(int[] a) 把數組轉成字符串 System.out.println("排序前:" + Arrays.toString(arr)); // public static void sort(int[] a) 對數組進行排序 Arrays.sort(arr); System.out.println("排序后:" + Arrays.toString(arr)); // [13, 24, 57, 69, 80] // public static int binarySearch(int[] a,int key) 二分查找 System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57)); System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577)); } } ====================================================================== public static String toString(int[] a) public static void sort(int[] a) 底層是快速排序,知道就可以了。有空看,有問題再問我 public static int binarySearch(int[] a,int key) 開發原則: 只要是對象,我們就要判斷該對象是否為null。 int[] arr = { 24, 69, 80, 57, 13 }; System.out.println("排序前:" + Arrays.toString(arr)); public static String toString(int[] a) { //a -- arr -- { 24, 69, 80, 57, 13 } if (a == null) return "null"; //說明數組對象不存在 int iMax = a.length - 1; //iMax=4; if (iMax == -1) return "[]"; //說明數組存在,但是沒有元素。 StringBuilder b = new StringBuilder(); b.append('['); //"[" for (int i = 0; ; i++) { b.append(a[i]); //"[24, 69, 80, 57, 13" if (i == iMax) //"[24, 69, 80, 57, 13]" return b.append(']').toString(); b.append(", "); //"[24, 69, 80, 57, " } } ----------------------------------------------------- int[] arr = {13, 24, 57, 69, 80}; System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577)); public static int binarySearch(int[] a, int key) { //a -- arr -- {13, 24, 57, 69, 80} //key -- 577 return binarySearch0(a, 0, a.length, key); } private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { //a -- arr -- {13, 24, 57, 69, 80} //fromIndex -- 0 //toIndex -- 5 //key -- 577 int low = fromIndex; //low=0 int high = toIndex - 1; //high=4 while (low <= high) { int mid = (low + high) >>> 1; //mid=2,mid=3,mid=4 int midVal = a[mid]; //midVal=57,midVal=69,midVal=80 if (midVal < key) low = mid + 1; //low=3,low=4,low=5 else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } ================================================================= package cn.itcast_01; /* * Character 類在對象中包裝一個基本類型 char 的值 * 此外,該類提供了幾種方法,以確定字符的類別(小寫字母,數字,等等),并將字符從大寫轉換成小寫,反之亦然 * * 構造方法: * Character(char value) */ public class CharacterDemo { public static void main(String[] args) { // 創建對象 // Character ch = new Character((char) 97); Character ch = new Character('a'); System.out.println("ch:" + ch); } } ======================================================================== package cn.itcast_02; /* * public static boolean isUpperCase(char ch):判斷給定的字符是否是大寫字符 * public static boolean isLowerCase(char ch):判斷給定的字符是否是小寫字符 * public static boolean isDigit(char ch):判斷給定的字符是否是數字字符 * public static char toUpperCase(char ch):把給定的字符轉換為大寫字符 * public static char toLowerCase(char ch):把給定的字符轉換為小寫字符 */ public class CharacterDemo { public static void main(Stri ng[] args) { // public static boolean isUpperCase(char ch):判斷給定的字符是否是大寫字符 System.out.println("isUpperCase:" + Character.isUpperCase('A')); System.out.println("isUpperCase:" + Character.isUpperCase('a')); System.out.println("isUpperCase:" + Character.isUpperCase('0')); System.out.println("-----------------------------------------"); // public static boolean isLowerCase(char ch):判斷給定的字符是否是小寫字符 System.out.println("isLowerCase:" + Character.isLowerCase('A')); System.out.println("isLowerCase:" + Character.isLowerCase('a')); System.out.println("isLowerCase:" + Character.isLowerCase('0')); System.out.println("-----------------------------------------"); // public static boolean isDigit(char ch):判斷給定的字符是否是數字字符 System.out.println("isDigit:" + Character.isDigit('A')); System.out.println("isDigit:" + Character.isDigit('a')); System.out.println("isDigit:" + Character.isDigit('0')); System.out.println("-----------------------------------------"); // public static char toUpperCase(char ch):把給定的字符轉換為大寫字符 System.out.println("toUpperCase:" + Character.toUpperCase('A')); System.out.println("toUpperCase:" + Character.toUpperCase('a')); System.out.println("-----------------------------------------"); // public static char toLowerCase(char ch):把給定的字符轉換為小寫字符 System.out.println("toLowerCase:" + Character.toLowerCase('A')); System.out.println("toLowerCase:" + Character.toLowerCase('a')); } } =========================================================================== package cn.itcast_03; import java.util.Scanner; /* * 統計一個字符串中大寫字母字符,小寫字母字符,數字字符出現的次數。(不考慮其他字符) * * 分析: * A:定義三個統計變量。 * int bigCont=0; * int smalCount=0; * int numberCount=0; * B:鍵盤錄入一個字符串。 * C:把字符串轉換為字符數組。 * D:遍歷字符數組獲取到每一個字符 * E:判斷該字符是 * 大寫 bigCount++; * 小寫 smalCount++; * 數字 numberCount++; * F:輸出結果即可 */ public class CharacterTest { public static void main(String[] args) { // 定義三個統計變量。 int bigCount = 0; int smallCount = 0; int numberCount = 0; // 鍵盤錄入一個字符串。 Scanner sc = new Scanner(System.in); System.out.println("請輸入一個字符串:"); String line = sc.nextLine(); // 把字符串轉換為字符數組。 char[] chs = line.toCharArray(); // 歷字符數組獲取到每一個字符 for (int x = 0; x < chs.length; x++) { char ch = chs[x]; // 判斷該字符 if (Character.isUpperCase(ch)) { bigCount++; } else if (Character.isLowerCase(ch)) { smallCount++; } else if (Character.isDigit(ch)) { numberCount++; } } // 輸出結果即可 System.out.println("大寫字母:" + bigCount + "個"); System.out.println("小寫字母:" + smallCount + "個"); System.out.println("數字字符:" + numberCount + "個"); } } ================================================================ package cn.itcast_01; / public class IntegerDemo { public static void main(String[] args) { // 不麻煩的就來了 // public static String toBinaryString(int i) System.out.println(Integer.toBinaryString(100)); // public static String toOctalString(int i) System.out.println(Integer.toOctalString(100)); // public static String toHexString(int i) System.out.println(Integer.toHexString(100)); // public static final int MAX_VALUE System.out.println(Integer.MAX_VALUE); // public static final int MIN_VALUE System.out.println(Integer.MIN_VALUE); } } 1100100 144 64 2147483647 -2147483648 ======================================================================== package cn.itcast_02; /* * Integer的構造方法: * public Integer(int value) * public Integer(String s) * 注意:這個字符串必須是由數字字符組成 */ public class IntegerDemo { public static void main(String[] args) { // 方式1 int i = 100; Integer ii = new Integer(i); System.out.println("ii:" + ii); // 方式2 String s = "100"; // NumberFormatException // String s = "abc"; Integer iii = new Integer(s); System.out.println("iii:" + iii); } } ===========================================================================s1:100 s2:100 s3:100 s4:100 ----------------- x:100 y:100 ========================================== package cn.itcast_04; /* * 常用的基本進制轉換 * public static String toBinaryString(int i) * public static String toOctalString(int i) * public static String toHexString(int i) * * 十進制到其他進制 * public static String toString(int i,int radix) * 由這個我們也看到了進制的范圍:2-36 * 為什么呢?0,...9,a...z * * 其他進制到十進制 * public static int parseInt(String s,int radix) */ public class IntegerDemo { public static void main(String[] args) { // 十進制到二進制,八進制,十六進制 System.out.println(Integer.toBinaryString(100)); System.out.println(Integer.toOctalString(100)); System.out.println(Integer.toHexString(100)); System.out.println("-------------------------"); // 十進制到其他進制 System.out.println(Integer.toString(100, 10)); System.out.println(Integer.toString(100, 2)); System.out.println(Integer.toString(100, 8)); System.out.println(Integer.toString(100, 16)); System.out.println(Integer.toString(100, 5)); System.out.println(Integer.toString(100, 7)); System.out.println(Integer.toString(100, -7)); System.out.println(Integer.toString(100, 70)); System.out.println(Integer.toString(100, 1)); System.out.println(Integer.toString(100, 17)); System.out.println(Integer.toString(100, 32)); System.out.println(Integer.toString(100, 37)); System.out.println(Integer.toString(100, 36)); System.out.println("-------------------------"); //其他進制到十進制 System.out.println(Integer.parseInt("100", 10)); System.out.println(Integer.parseInt("100", 2)); System.out.println(Integer.parseInt("100", 8)); System.out.println(Integer.parseInt("100", 16)); System.out.println(Integer.parseInt("100", 23)); //NumberFormatException //System.out.println(Integer.parseInt("123", 2)); } } ======================================================================= package cn.itcast_05; /* * JDK5的新特性 * 自動裝箱:把基本類型轉換為包裝類類型 * 自動拆箱:把包裝類類型轉換為基本類型 * * 注意一個小問題: * 在使用時,Integer x = null;代碼就會出現NullPointerException。 * 建議先判斷是否為null,然后再使用。 */ public class IntegerDemo { public static void main(String[] args) { // 定義了一個int類型的包裝類類型變量i // Integer i = new Integer(100); Integer ii = 100; ii += 200; System.out.println("ii:" + ii); // 通過反編譯后的代碼 // Integer ii = Integer.valueOf(100); //自動裝箱 // ii = Integer.valueOf(ii.intValue() + 200); //自動拆箱,再自動裝箱 // System.out.println((new StringBuilder("ii:")).append(ii).toString()); Integer iii = null; // NullPointerException if (iii != null) { iii += 1000; System.out.println(iii); } } } ===========================================================================package cn.itcast_06; /* * 看程序寫結果 * * 注意:Integer的數據直接賦值,如果在-128到127之間,會直接從緩沖池里獲取數據 */ public class IntegerDemo { public static void main(String[] args) { Integer i1 = new Integer(127); Integer i2 = new Integer(127); System.out.println(i1 == i2); System.out.println(i1.equals(i2)); System.out.println("-----------"); Integer i3 = new Integer(128); Integer i4 = new Integer(128); System.out.println(i3 == i4); System.out.println(i3.equals(i4)); System.out.println("-----------"); Integer i5 = 128; Integer i6 = 128; System.out.println(i5 == i6); System.out.println(i5.equals(i6)); System.out.println("-----------"); Integer i7 = 127; Integer i8 = 127; System.out.println(i7 == i8); System.out.println(i7.equals(i8)); // 通過查看源碼,我們就知道了,針對-128到127之間的數據,做了一個數據緩沖池,如果數據是該范圍內的,每次并不創建新的空間 // Integer ii = Integer.valueOf(127); } } false true ----------- false true ----------- false true ----------- true true ======================================================================== package cn.itcast_01; System.out.println("--------------------------"); // public StringBuffer(int capacity):指定容量的字符串緩沖區對象 StringBuffer sb2 = new StringBuffer(50); System.out.println("sb2:" + sb2); System.out.println("sb2.capacity():" + sb2.capacity()); System.out.println("sb2.length():" + sb2.length()); System.out.println("--------------------------"); // public StringBuffer(String str):指定字符串內容的字符串緩沖區對象 StringBuffer sb3 = new StringBuffer("hello"); System.out.println("sb3:" + sb3); System.out.println("sb3.capacity():" + sb3.capacity()); System.out.println("sb3.length():" + sb3.length()); } } ======================================= package cn.itcast_02; /* * StringBuffer的添加功能: * public StringBuffer append(String str):可以把任意類型數據添加到字符串緩沖區里面,并返回字符串緩沖區本身 * * public StringBuffer insert(int offset,String str):在指定位置把任意類型的數據插入到字符串緩沖區里面,并返回字符串緩沖區本身 */ public class StringBufferDemo { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); // public StringBuffer append(String str) // StringBuffer sb2 = sb.append("hello"); // System.out.println("sb:" + sb); // System.out.println("sb2:" + sb2); // System.out.println(sb == sb2); // true // 一步一步的添加數據 // sb.append("hello"); // sb.append(true); // sb.append(12); // sb.append(34.56); // 鏈式編程 sb.append("hello").append(true).append(12).append(34.56); System.out.println("sb:" + sb); // public StringBuffer insert(int offset,String // str):在指定位置把任意類型的數據插入到字符串緩沖區里面,并返回字符串緩沖區本身 sb.insert(5, "world"); System.out.println("sb:" + sb); } } ========================================================= package cn.itcast_03; /* * StringBuffer的刪除功能 * public StringBuffer deleteCharAt(int index):刪除指定位置的字符,并返回本身 * public StringBuffer delete(int start,int end):刪除從指定位置開始指定位置結束的內容,并返回本身 */ public class StringBufferDemo { public static void main(String[] args) { // 創建對象 StringBuffer sb = new StringBuffer(); // 添加功能 sb.append("hello").append("world").append("java"); System.out.println("sb:" + sb); // public StringBuffer deleteCharAt(int index):刪除指定位置的字符,并返回本身 // 需求:我要刪除e這個字符,腫么辦? // sb.deleteCharAt(1); // 需求:我要刪除第一個l這個字符,腫么辦? // sb.deleteCharAt(1); // public StringBuffer delete(int start,int // end):刪除從指定位置開始指定位置結束的內容,并返回本身 // 需求:我要刪除world這個字符串,腫么辦?包左不包右邊 // sb.delete(5, 10); // 需求:我要刪除所有的數據 sb.delete(0, sb.length()); System.out.println("sb:" + sb); } } ===================================================================== package cn.itcast_04; /* * StringBuffer的替換功能: * public StringBuffer replace(int start,int end,String str):從start開始到end用str替換 */ public class StringBufferDemo { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); // 添加數據 sb.append("hello"); sb.append("world"); sb.append("java"); System.out.println("sb:" + sb); // public StringBuffer replace(int start,int end,String // str):從start開始到end用str替換 // 需求:我要把world這個數據替換為"節日快樂" sb.replace(5, 10, "節日快樂"); System.out.println("sb:" + sb); } } ===================================================================== package cn.itcast_05; /* * StringBuffer的反轉功能: * public StringBuffer reverse() */ public class StringBufferDemo { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); // 添加數據 sb.append("霞青林愛我"); System.out.println("sb:" + sb); // public StringBuffer reverse() sb.reverse(); System.out.println("sb:" + sb); } } ================================================================ package cn.itcast_06; /* * StringBuffer的截取功能:注意返回值類型不再是StringBuffer本身了 * public String substring(int start) * public String substring(int start,int end) */ public class StringBufferDemo { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); // 添加元素 sb.append("hello").append("world").append("java"); System.out.println("sb:" + sb); // 截取功能 // public String substring(int start) String s = sb.substring(5); System.out.println("s:" + s); System.out.println("sb:" + sb); // public String substring(int start,int end) String ss = sb.substring(5, 10); System.out.println("ss:" + ss); System.out.println("sb:" + sb); } } ===================================== package cn.itcast_07; /* * 為什么我們要講解類之間的轉換: * A -- B的轉換 * 我們把A轉換為B,其實是為了使用B的功能。 * B -- A的轉換 * 我們可能要的結果是A類型,所以還得轉回來。 * * String和StringBuffer的相互轉換? */ public class StringBufferTest { public static void main(String[] args) { // String -- StringBuffer String s = "hello"; // 注意:不能把字符串的值直接賦值給StringBuffer // StringBuffer sb = "hello"; // StringBuffer sb = s; // 方式1:通過構造方法 StringBuffer sb = new StringBuffer(s); // 方式2:通過append()方法 StringBuffer sb2 = new StringBuffer(); sb2.append(s); System.out.println("sb:" + sb); System.out.println("sb2:" + sb2); System.out.println("---------------"); // StringBuffer -- String StringBuffer buffer = new StringBuffer("java"); // String(StringBuffer buffer) // 方式1:通過構造方法 String str = new String(buffer); // 方式2:通過toString()方法 String str2 = buffer.toString(); System.out.println("str:" + str); System.out.println("str2:" + str2); } } ===========================================================================package cn.itcast_07; /* * 把數組拼接成一個字符串 */ public class StringBufferTest2 { public static void main(String[] args) { // 定義一個數組 int[] arr = { 44, 33, 55, 11, 22 }; // 定義功能 // 方式1:用String做拼接的方式 String s1 = arrayToString(arr); System.out.println("s1:" + s1); // 方式2:用StringBuffer做拼接的方式 String s2 = arrayToString2(arr); System.out.println("s2:" + s2); } // 用StringBuffer做拼接的方式 public static String arrayToString2(int[] arr) { StringBuffer sb = new StringBuffer(); sb.append("["); for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { sb.append(arr[x]); } else { sb.append(arr[x]).append(", "); } } sb.append("]"); return sb.toString(); } // 用String做拼接的方式 public static String arrayToString(int[] arr) { String s = ""; s += "["; for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { s += arr[x]; } else { s += arr[x]; s += ", "; } } s += "]"; return s; } } =================================================================== package cn.itcast_07; import java.util.Scanner; /* * 把字符串反轉 */ public class StringBufferTest3 { public static void main(String[] args) { // 鍵盤錄入數據 Scanner sc = new Scanner(System.in); System.out.println("請輸入數據:"); String s = sc.nextLine(); // 方式1:用String做拼接 String s1 = myReverse(s); System.out.println("s1:" + s1); // 方式2:用StringBuffer的reverse()功能 String s2 = myReverse2(s); System.out.println("s2:" + s2); } // 用StringBuffer的reverse()功能 public static String myReverse2(String s) { // StringBuffer sb = new StringBuffer(); // sb.append(s); // StringBuffer sb = new StringBuffer(s); // sb.reverse(); // return sb.toString(); // 簡易版 return new StringBuffer(s).reverse().toString(); } // 用String做拼接 public static String myReverse(String s) { String result = ""; char[] chs = s.toCharArray(); for (int x = chs.length - 1; x >= 0; x--) { // char ch = chs[x]; // result += ch; result += chs[x]; } return result; } } ===================================================================== package cn.itcast_08; /* * 面試題: * 1:String,StringBuffer,StringBuilder的區別? * A:String是內容不可變的,而StringBuffer,StringBuilder都是內容可變的。 * B:StringBuffer是同步的,數據安全,效率低;StringBuilder是不同步的,數據不安全,效率高 * * 2:StringBuffer和數組的區別? * 二者都可以看出是一個容器,裝其他的數據。 * 但是呢,StringBuffer的數據最終是一個字符串數據。 * 而數組可以放置多種數據,但必須是同一種數據類型的。 * * 3:形式參數問題 * String作為參數傳遞 * StringBuffer作為參數傳遞 * * 形式參數: * 基本類型:形式參數的改變不影響實際參數 * 引用類型:形式參數的改變直接影響實際參數 * * 注意: * String作為參數傳遞,效果和基本類型作為參數傳遞是一樣的。不變的 */ public class StringBufferDemo { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; System.out.println(s1 + "---" + s2);// hello---world change(s1, s2);//常量 System.out.println(s1 + "---" + s2);// hello---world StringBuffer sb1 = new StringBuffer("hello"); StringBuffer sb2 = new StringBuffer("world"); System.out.println(sb1 + "---" + sb2);// hello---world change(sb1, sb2); System.out.println(sb1 + "---" + sb2);// hello---worldworld } public static void change(StringBuffer sb1, StringBuffer sb2) { sb1 = sb2; sb2.append(sb1); } public static void change(String s1, String s2) { s1 = s2; s2 = s1 + s2; } } 3.BigDecimal Calendar Math System package cn.itcast_01; /* * 看程序寫結果:結果和我們想的有一點點不一樣,這是因為float類型的數據存儲和整數不一樣導致的。它們大部分的時候,都是帶有有效數字位。 * * 由于在運算的時候,float類型和double很容易丟失精度,演示案例。所以,為了能精確的表示、計算浮點數,Java提供了BigDecimal * * BigDecimal類:不可變的、任意精度的有符號十進制數,可以解決數據丟失問題。 */ public class BigDecimalDemo { public static void main(String[] args) { System.out.println(0.09 + 0.01); System.out.println(1.0 - 0.32); System.out.println(1.015 * 100); System.out.println(1.301 / 100); System.out.println(1.0 - 0.12); } } ======================================================================== package cn.itcast_02; import java.math.BigDecimal; /* * 構造方法: * public BigDecimal(String val) * * public BigDecimal add(BigDecimal augend) * public BigDecimal subtract(BigDecimal subtrahend) * public BigDecimal multiply(BigDecimal multiplicand) * public BigDecimal divide(BigDecimal divisor) * public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,幾位小數,如何舍取 */ public class BigDecimalDemo { public static void main(String[] args) { // System.out.println(0.09 + 0.01); // System.out.println(1.0 - 0.32); // System.out.println(1.015 * 100); // System.out.println(1.301 / 100); BigDecimal bd1 = new BigDecimal("0.09"); BigDecimal bd2 = new BigDecimal("0.01"); System.out.println("add:" + bd1.add(bd2)); System.out.println("-------------------"); BigDecimal bd3 = new BigDecimal("1.0"); BigDecimal bd4 = new BigDecimal("0.32"); System.out.println("subtract:" + bd3.subtract(bd4)); System.out.println("-------------------"); BigDecimal bd5 = new BigDecimal("1.015"); BigDecimal bd6 = new BigDecimal("100"); System.out.println("multiply:" + bd5.multiply(bd6)); System.out.println("-------------------"); BigDecimal bd7 = new BigDecimal("1.301"); BigDecimal bd8 = new BigDecimal("100"); System.out.println("divide:" + bd7.divide(bd8)); System.out.println("divide:" + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP)); System.out.println("divide:" + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP)); } } =========================================== package cn.itcast_02; import java.math.BigDecimal; /* * 構造方法: * public BigDecimal(String val) * * public BigDecimal add(BigDecimal augend) * public BigDecimal subtract(BigDecimal subtrahend) * public BigDecimal multiply(BigDecimal multiplicand) * public BigDecimal divide(BigDecimal divisor) * public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,幾位小數,如何舍取 */ public class BigDecimalDemo { public static void main(String[] args) { // System.out.println(0.09 + 0.01); // System.out.println(1.0 - 0.32); // System.out.println(1.015 * 100); // System.out.println(1.301 / 100); BigDecimal bd1 = new BigDecimal("0.09"); BigDecimal bd2 = new BigDecimal("0.01"); System.out.println("add:" + bd1.add(bd2)); System.out.println("-------------------"); BigDecimal bd3 = new BigDecimal("1.0"); BigDecimal bd4 = new BigDecimal("0.32"); System.out.println("subtract:" + bd3.subtract(bd4)); System.out.println("-------------------"); BigDecimal bd5 = new BigDecimal("1.015"); BigDecimal bd6 = new BigDecimal("100"); System.out.println("multiply:" + bd5.multiply(bd6)); System.out.println("-------------------"); BigDecimal bd7 = new BigDecimal("1.301"); BigDecimal bd8 = new BigDecimal("100"); System.out.println("divide:" + bd7.divide(bd8)); System.out.println("divide:" + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP)); System.out.println("divide:" + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP)); } } =================================================== // 這幾個測試,是為了簡單超過int范圍內,Integer就不能再表示,所以就更談不上計算了。 // Integer i = new Integer(100); // System.out.println(i); // // System.out.println(Integer.MAX_VALUE); // Integer ii = new Integer("2147483647"); // System.out.println(ii); // // NumberFormatException // Integer iii = new Integer("2147483648"); // System.out.println(iii); // 通過大整數來創建對象 BigInteger bi = new BigInteger("2147483648"); System.out.println("bi:" + bi); ========================================================================= package cn.itcast_02; import java.math.BigInteger; /* * public BigInteger add(BigInteger val):加 * public BigInteger subtract(BigInteger val):減 * public BigInteger multiply(BigInteger val):乘 * public BigInteger divide(BigInteger val):除 * public BigInteger[] divideAndRemainder(BigInteger val):返回商和余數的數組 */ public class BigIntegerDemo { public static void main(String[] args) { BigInteger bi1 = new BigInteger("100"); BigInteger bi2 = new BigInteger("50"); // public BigInteger add(BigInteger val):加 System.out.println("add:" + bi1.add(bi2)); // public BigInteger subtract(BigInteger val):加 System.out.println("subtract:" + bi1.subtract(bi2)); // public BigInteger multiply(BigInteger val):加 System.out.println("multiply:" + bi1.multiply(bi2)); // public BigInteger divide(BigInteger val):加 System.out.println("divide:" + bi1.divide(bi2)); // public BigInteger[] divideAndRemainder(BigInteger val):返回商和余數的數組 BigInteger[] bis = bi1.divideAndRemainder(bi2); System.out.println("商:" + bis[0]); System.out.println("余數:" + bis[1]); } } ================================================== package cn.itcast_01; import java.util.Calendar; /* * Calendar:它為特定瞬間與一組諸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日歷字段之間的轉換提供了一些方法,并為操作日歷字段(例如獲得下星期的日期)提供了一些方法。 * * public int get(int field):返回給定日歷字段的值。日歷類中的每個日歷字段都是靜態的成員變量,并且是int類型。 */ public class CalendarDemo { public static void main(String[] args) { // 其日歷字段已由當前日期和時間初始化: Calendar rightNow = Calendar.getInstance(); // 子類對象 // 獲取年 int year = rightNow.get(Calendar.YEAR); // 獲取月 int month = rightNow.get(Calendar.MONTH); // 獲取日 int date = rightNow.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); } } /* * abstract class Person { public static Person getPerson() { return new * Student(); } } * * class Student extends Person { * * } */ ==================================================================== package cn.itcast_02; import java.util.Calendar; /* * public void add(int field,int amount):根據給定的日歷字段和對應的時間,來對當前的日歷進行操作。 * public final void set(int year,int month,int date):設置當前日歷的年月日 */ public class CalendarDemo { public static void main(String[] args) { // 獲取當前的日歷時間 Calendar c = Calendar.getInstance(); // 獲取年 int year = c.get(Calendar.YEAR); // 獲取月 int month = c.get(Calendar.MONTH); // 獲取日 int date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // // 三年前的今天 // c.add(Calendar.YEAR, -3); // // 獲取年 // year = c.get(Calendar.YEAR); // // 獲取月 // month = c.get(Calendar.MONTH); // // 獲取日 // date = c.get(Calendar.DATE); // System.out.println(year + "年" + (month + 1) + "月" + date + "日"); // 5年后的10天前 c.add(Calendar.YEAR, 5); c.add(Calendar.DATE, -10); // 獲取年 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); System.out.println("--------------"); c.set(2011, 11, 11); // 獲取年 year = c.get(Calendar.YEAR); // 獲取月 month = c.get(Calendar.MONTH); // 獲取日 date = c.get(Calendar.DATE); System.out.println(year + "年" + (month + 1) + "月" + date + "日"); } } ===========================================================================package cn.itcast_03; import java.util.Calendar; import java.util.Scanner; /* * 獲取任意一年的二月有多少天 * * 分析: * A:鍵盤錄入任意的年份 * B:設置日歷對象的年月日 * 年就是A輸入的數據 * 月是2 * 日是1 * C:把時間往前推一天,就是2月的最后一天 * D:獲取這一天輸出即可 */ public class CalendarTest { public static void main(String[] args) { // 鍵盤錄入任意的年份 Scanner sc = new Scanner(System.in); System.out.println("請輸入年份:"); int year = sc.nextInt(); // 設置日歷對象的年月日 Calendar c = Calendar.getInstance(); c.set(year, 2, 1); // 其實是這一年的3月1日 // 把時間往前推一天,就是2月的最后一天 c.add(Calendar.DATE, -1); // 獲取這一天輸出即可 System.out.println(c.get(Calendar.DATE)); } } ================================================================ package cn.itcast_01; import java.util.Date; /* * Date:表示特定的瞬間,精確到毫秒。 * * 構造方法: * Date():根據當前的默認毫秒值創建日期對象 * Date(long date):根據給定的毫秒值創建日期對象 */ public class DateDemo { public static void main(String[] args) { // 創建對象 Date d = new Date(); System.out.println("d:" + d); // 創建對象 // long time = System.currentTimeMillis(); long time = 1000 * 60 * 60; // 1小時 Date d2 = new Date(time); System.out.println("d2:" + d2); } } ============================================================== package cn.itcast_02; import java.util.Date; /* * public long getTime():獲取時間,以毫秒為單位 * public void setTime(long time):設置時間 * * 從Date得到一個毫秒值 * getTime() * 把一個毫秒值轉換為Date * 構造方法 * setTime(long time) */ public class DateDemo { public static void main(String[] args) { // 創建對象 Date d = new Date(); // 獲取時間 long time = d.getTime(); System.out.println(time); // System.out.println(System.currentTimeMillis()); System.out.println("d:" + d); // 設置時間 d.setTime(1000); System.out.println("d:" + d); } } ======================================================= package cn.itcast_03; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /* * Date -- String(格式化) * public final String format(Date date) * * String -- Date(解析) * public Date parse(String source) * * DateForamt:可以進行日期和字符串的格式化和解析,但是由于是抽象類,所以使用具體子類SimpleDateFormat。 * * SimpleDateFormat的構造方法: * SimpleDateFormat():默認模式 * SimpleDateFormat(String pattern):給定的模式 * 這個模式字符串該如何寫呢? * 通過查看API,我們就找到了對應的模式 * 年 y * 月 M * 日 d * 時 H * 分 m * 秒 s * * 2014年12月12日 12:12:12 */ public class DateFormatDemo { public static void main(String[] args) throws ParseException { // Date -- String // 創建日期對象 Date d = new Date(); // 創建格式化對象 // SimpleDeFormat sdf = new SimpleDateFormat(); // 給定模式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // public final String format(Date date) String s = sdf.format(d); System.out.println(s); //String -- Date String str = "2008-08-08 12:12:12"; //在把一個字符串解析為日期的時候,請注意格式必須和給定的字符串格式匹配 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dd = sdf2.parse(str); System.out.println(dd); } } ===========================================================================package cn.itcast_04; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 這是日期和字符串相互轉換的工具類 * * @author 風清揚 */ public class DateUtil { private DateUtil() { } /** * 這個方法的作用就是把日期轉成一個字符串 * * @param d * 被轉換的日期對象 * @param format * 傳遞過來的要被轉換的格式 * @return 格式化后的字符串 */ public static String dateToString(Date d, String format) { // SimpleDateFormat sdf = new SimpleDateFormat(format); // return sdf.format(d); return new SimpleDateFormat(format).format(d); } /** * 這個方法的作用就是把一個字符串解析成一個日期對象 * * @param s * 被解析的字符串 * @param format * 傳遞過來的要被轉換的格式 * @return 解析后的日期對象 * @throws ParseException */ public static Date stringToDate(String s, String format) throws ParseException { return new SimpleDateFormat(format).parse(s); } } ============================================================ package cn.itcast_04; import java.text.ParseException; import java.util.Date; /* * 工具類的測試 */ public class DateUtilDemo { public static void main(String[] args) throws ParseException { Date d = new Date(); // yyyy-MM-dd HH:mm:ss String s = DateUtil.dateToString(d, "yyyy年MM月dd日 HH:mm:ss"); System.out.println(s); String s2 = DateUtil.dateToString(d, "yyyy年MM月dd日"); System.out.println(s2); String s3 = DateUtil.dateToString(d, "HH:mm:ss"); System.out.println(s3); String str = "2014-10-14"; Date dd = DateUtil.stringToDate(str, "yyyy-MM-dd"); System.out.println(dd); } } =============================================================== package cn.itcast_05; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /* * 算一下你來到這個世界多少天? * * 分析: * A:鍵盤錄入你的出生的年月日 * B:把該字符串轉換為一個日期 * C:通過該日期得到一個毫秒值 * D:獲取當前時間的毫秒值 * E:用D-C得到一個毫秒值 * F:把E的毫秒值轉換為年 * /1000/60/60/24 */ public class MyYearOldDemo { public static void main(String[] args) throws ParseException { // 鍵盤錄入你的出生的年月日 Scanner sc = new Scanner(System.in); System.out.println("請輸入你的出生年月日:"); String line = sc.nextLine(); // 把該字符串轉換為一個日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(line); // 通過該日期得到一個毫秒值 long myTime = d.getTime(); // 獲取當前時間的毫秒值 long nowTime = System.currentTimeMillis(); // 用D-C得到一個毫秒值 long time = nowTime - myTime; // 把E的毫秒值轉換為年 long day = time / 1000 / 60 / 60 / 24; System.out.println("你來到這個世界:" + day + "天"); } } =========================================================================== package cn.itcast_01; /* * Math:用于數學運算的類。 * 成員變量: * public static final double PI * public static final double E * 成員方法: * public static int abs(int a):絕對值 * public static double ceil(double a):向上取整 * public static double floor(double a):向下取整 * public static int max(int a,int b):最大值 (min自學) * public static double pow(double a,double b):a的b次冪 * public static double random():隨機數 [0.0,1.0) * public static int round(float a) 四舍五入(參數為double的自學) * public static double sqrt(double a):正平方根 */ public class MathDemo { public static void main(String[] args) { // public static final double PI System.out.println("PI:" + Math.PI); // public static final double E System.out.println("E:" + Math.E); System.out.println("--------------"); // public static int abs(int a):絕對值 System.out.println("abs:" + Math.abs(10)); System.out.println("abs:" + Math.abs(-10)); System.out.println("--------------"); // public static double ceil(double a):向上取整 System.out.println("ceil:" + Math.ceil(12.34)); System.out.println("ceil:" + Math.ceil(12.56)); System.out.println("--------------"); // public static double floor(double a):向下取整 System.out.println("floor:" + Math.floor(12.34)); System.out.println("floor:" + Math.floor(12.56)); System.out.println("--------------"); // public static int max(int a,int b):最大值 System.out.println("max:" + Math.max(12, 23)); // 需求:我要獲取三個數據中的最大值 // 方法的嵌套調用 System.out.println("max:" + Math.max(Math.max(12, 23), 18)); // 需求:我要獲取四個數據中的最大值 System.out.println("max:" + Math.max(Math.max(12, 78), Math.max(34, 56))); System.out.println("--------------"); // public static double pow(double a,double b):a的b次冪 System.out.println("pow:" + Math.pow(2, 3)); System.out.println("--------------"); // public static double random():隨機數 [0.0,1.0) System.out.println("random:" + Math.random()); // 獲取一個1-100之間的隨機數 System.out.println("random:" + ((int) (Math.random() * 100) + 1)); System.out.println("--------------"); // public static int round(float a) 四舍五入(參數為double的自學) System.out.println("round:" + Math.round(12.34f)); System.out.println("round:" + Math.round(12.56f)); System.out.println("--------------"); //public static double sqrt(double a):正平方根 System.out.println("sqrt:"+Math.sqrt(4)); } } =========================================================================== package cn.itcast_02; import java.util.Scanner; /* * 需求:請設計一個方法,可以實現獲取任意范圍內的隨機數。 * * 分析: * A:鍵盤錄入兩個數據。 * int strat; * int end; * B:想辦法獲取在start到end之間的隨機數 * 我寫一個功能實現這個效果,得到一個隨機數。(int) * C:輸出這個隨機數 */ public class MathDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入開始數:"); int start = sc.nextInt(); System.out.println("請輸入結束數:"); int end = sc.nextInt(); for (int x = 0; x < 100; x++) { // 調用功能 int num = getRandom(start, end); // 輸出結果 System.out.println(num); } } /* * 寫一個功能 兩個明確: 返回值類型:int 參數列表:int start,int end */ public static int getRandom(int start, int end) { // 回想我們講過的1-100之間的隨機數 // int number = (int) (Math.random() * 100) + 1; // int number = (int) (Math.random() * end) + start; // 發現有問題了,怎么辦呢? return number; } } ====================================================== package cn.itcast_01; import java.util.Random; /* * Random:產生隨機數的類 * * 構造方法: * public Random():沒有給種子,用的是默認種子,是當前時間的毫秒值 * public Random(long seed):給出指定的種子 * * 給定種子后,每次得到的隨機數是相同的。 * * 成員方法: * public int nextInt():返回的是int范圍內的隨機數 * public int nextInt(int n):返回的是[0,n)范圍的內隨機數 */ public class RandomDemo { public static void main(String[] args) { // 創建對象 // Random r = new Random(); Random r = new Random(1111); for (int x = 0; x < 10; x++) { // int num = r.nextInt(); int num = r.nextInt(100) + 1; System.out.println(num); } } } ===========================================================================package cn.itcast_01; import java.util.Scanner; /* * 校驗qq號碼. * 1:要求必須是5-15位數字 * 2:0不能開頭 * * 分析: * A:鍵盤錄入一個QQ號碼 * B:寫一個功能實現校驗 * C:調用功能,輸出結果。 */ public class RegexDemo { public static void main(String[] args) { // 創建鍵盤錄入對象 Scanner sc = new Scanner(System.in); System.out.println("請輸入你的QQ號碼:"); String qq = sc.nextLine(); System.out.println("checkQQ:"+checkQQ(qq)); } /* * 寫一個功能實現校驗 兩個明確: 明確返回值類型:boolean 明確參數列表:String qq */ public static boolean checkQQ(String qq) { boolean flag = true; // 校驗長度 if (qq.length() >= 5 && qq.length() <= 15) { // 0不能開頭 if (!qq.startsWith("0")) { // 必須是數字 char[] chs = qq.toCharArray(); for (int x = 0; x < chs.length; x++) { char ch = chs[x]; if (!Character.isDigit(ch)) { flag = false; break; } } } else { flag = false; } } else { flag = false; } return flag; } } ===========================================================================package cn.itcast_01; import java.util.Scanner; /* * 正則表達式:符合一定規則的字符串。 */ public class RegexDemo2 { public static void main(String[] args) { // 創建鍵盤錄入對象 Scanner sc = new Scanner(System.in); System.out.println("請輸入你的QQ號碼:"); String qq = sc.nextLine(); System.out.println("checkQQ:" + checkQQ(qq)); } public static boolean checkQQ(String qq) { // String regex ="[1-9][0-9]{4,14}"; // //public boolean matches(String regex)告知此字符串是否匹配給定的正則表達式 // boolean flag = qq.matches(regex); // return flag; //return qq.matches("[1-9][0-9]{4,14}"); return qq.matches("[1-9]\\d{4,14}"); } } ========================================================== package cn.itcast_02; import java.util.Scanner; /* * 判斷功能 * String類的public boolean matches(String regex) * * 需求: * 判斷手機號碼是否滿足要求? * * 分析: * A:鍵盤錄入手機號碼 * B:定義手機號碼的規則 * 13436975980 * 13688886868 * 13866668888 * 13456789012 * 13123456789 * 18912345678 * 18886867878 * 18638833883 * C:調用功能,判斷即可 * D:輸出結果 */ public class RegexDemo { public static void main(String[] args) { //鍵盤錄入手機號碼 Scanner sc = new Scanner(System.in); System.out.println("請輸入你的手機號碼:"); String phone = sc.nextLine(); //定義手機號碼的規則 String regex = "1[38]\\d{9}"; //調用功能,判斷即可 boolean flag = phone.matches(regex); //輸出結果 System.out.println("flag:"+flag); } } ==================================================== package cn.itcast_02; import java.util.Scanner; /* * 校驗郵箱 * * 分析: * A:鍵盤錄入郵箱 * B:定義郵箱的規則 * 1517806580@qq.com * liuyi@163.com * linqingxia@126.com * fengqingyang@sina.com.cn * fqy@itcast.cn * C:調用功能,判斷即可 * D:輸出結果 */ public class RegexTest { public static void main(String[] args) { //鍵盤錄入郵箱 Scanner sc = new Scanner(System.in); System.out.println("請輸入郵箱:"); String email = sc.nextLine(); //定義郵箱的規則 //String regex = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]{2,3})+"; String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+"; //調用功能,判斷即可 boolean flag = email.matches(regex); //輸出結果 System.out.println("flag:"+flag); } } ======================================================== A:字符 x 字符 x。舉例:'a'表示字符a \\ 反斜線字符。 \n 新行(換行)符 ('\u000A') \r 回車符 ('\u000D') B:字符類 [abc] a、b 或 c(簡單類) [^abc] 任何字符,除了 a、b 或 c(否定) [a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(范圍) [0-9] 0到9的字符都包括 如:[1-9][0-9]{4,14}表示:第一個數[1-9]表示1到9,第二個數[0-9]表示0到9 {4,14}表示[0-9]有4位到14位 C:預定義字符類 . 任何字符。我的就是.字符本身,怎么表示呢? \. \d 數字:[0-9] \w 單詞字符: [a-zA-Z_0-9] 在正則表達式里面組成單詞的東西必須有這些東西組成 D:邊界匹配器 ^ 行的開頭 $ 行的結尾 \b 單詞邊界 就是不是單詞字符的地方。 舉例:hello world?haha;xixi E:Greedy 數量詞 X? X,一次或一次也沒有 X* X,零次或多次 X+ X,一次或多次 X{n} X,恰好 n 次 X{n,} X,至少 n 次 X{n,m} X,至少 n 次,但是不超過 m 次 ========================================================================== package cn.itcast_01; public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } @Override protected void finalize() throws Throwable { System.out.println("當前的對象被回收了" + this); super.finalize(); } } === package cn.itcast_01; /* * System類包含一些有用的類字段和方法。它不能被實例化。 * * 方法: * public static void gc():運行垃圾回收器。 * public static void exit(int status) * public static long currentTimeMillis() * public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) */ public class SystemDemo { public static void main(String[] args) { checkQQ } } =========================================================================== package cn.itcast_02; /* * System類包含一些有用的類字段和方法。它不能被實例化。 * * 方法: * public static void gc():運行垃圾回收器。 * public static void exit(int status):終止當前正在運行的 Java 虛擬機。參數用作狀態碼;根據慣例,非 0 的狀態碼表示異常終止。 * public static long currentTimeMillis():返回以毫秒為單位的當前時間 * public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) */ public class SystemDemo { public static void main(String[] args) { // System.out.println("我們喜歡林青霞(東方不敗)"); // System.exit(0); // System.out.println("我們也喜歡趙雅芝(白娘子)"); // System.out.println(System.currentTimeMillis()); // 單獨得到這樣的實際目前對我們來說意義不大 // 那么,它到底有什么作用呢? // 要求:請大家給我統計這段程序的運行時間 long start = System.currentTimeMillis(); for (int x = 0; x < 100000; x++) { System.out.println("hello" + x); } long end = System.currentTimeMillis(); System.out.println("共耗時:" + (end - start) + "毫秒"); } } ============================================================= package cn.itcast_03; import java.util.Arrays; /* * System類包含一些有用的類字段和方法。它不能被實例化。 * * 方法: * public static void gc():運行垃圾回收器。 * public static void exit(int status):終止當前正在運行的 Java 虛擬機。參數用作狀態碼;根據慣例,非 0 的狀態碼表示異常終止。 * public static long currentTimeMillis():返回以毫秒為單位的當前時間 * public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) * 從指定源數組中復制一個數組,復制從指定的位置開始,到目標數組的指定位置結束。 */ public class SystemDemo { public static void main(String[] args) { // 定義數組 int[] arr = { 11, 22, 33, 44, 55 }; int[] arr2 = { 6, 7, 8, 9, 10 }; // 請大家看這個代碼的意思 System.arraycopy(arr, 1, arr2, 2, 2); System.out.println(Arrays.toString(arr)); System.out.println(Arrays.toString(arr2)); } }轉載于:https://www.cnblogs.com/yejibigdata/p/7835112.html
總結
以上是生活随笔為你收集整理的Java_String_Arrays_Character_BigDecimal_Calendar_Math_System的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Tengine + BabaSSL ,让
- 下一篇: 七牛云获取token中的bucket是什