------- android培訓、java培訓、期待與您交流! ----------
12.01 Scanner的概述和構造方法原理
Scanner類概述:JDK5以后用于獲取用戶的鍵盤輸入
構造方法:public Scanner(InputStreamsource)
public static final InputStream in:“標準”輸入流。
此流已打開并準備提供輸入數據。通常,此流對應于鍵盤輸入或者由主機環境或用戶指定的另一個輸入源。
12.02 Scanner類的hasNextXxx()和nextXxx()方法的講解
基本格式:
hasNextXxx():判斷是否還有下一個輸入項,其中Xxx可以是Int,Double等。
如果需要判斷是否包含下一個字符串,則可以省略Xxx
nextXxx():獲取下一個輸入項。Xxx的含義和上個方法中的Xxx相同
默認情況下,Scanner使用空格,回車等作為分隔符
常用方法:
public int nextInt(int radix):將輸入信息的下一個標記掃描為一個int
public String nextLine():此掃描器執行當前行,并返回跳過的輸入信息。此方法返回當前行的其余部分,不包括結尾處的行分隔符。
12.03 Scanner獲取數據出現的小問題及解決方案
例:
1 //先獲取一個int值,再獲取一個字符串2 Scanner sc = new Scanner(System.in);3 int x = sc.nextInt();4 String s = sc.nextLine();5 System.out.運行結果:
10x:10 s:上例中先獲取一個int值,再獲取一個字符串時,字符串的值是空的,因為Scanner使用空格回車等作為分隔符,當回車換行時將換行符號賦給了s
解決方案:
1:重新創建對象
2:都以字符串形式接收,然后把字符串轉成int類型
12.04 String類的概述
String類概述:字符串是由多個字符組成的一串數據(字符序列),字符串可以看成是字符數組,字符串是常量;它們的值在創建之后不能更改。
12.05 String類的構造方法
構造方法:
1. public String():
初始化一個新創建的 String 對象,使其表示一個空字符序列。注意,由于 String 是不可變的,所以無需使用此構造方法
2. public String(byte[] bytes):
通過使用平臺的默認字符集解碼指定的 byte 數組,構造一個新的 String
3. public String(byte[] bytes,int offset,int length):
通過使用平臺的默認字符集解碼指定的 byte 子數組,構造一個新的 String
4. public String(char[] value):
分配一個新的 String,使其表示字符數組參數中當前包含的字符序列
5. public String(char[] value,int offset,int count):
分配一個新的 String,它包含取自字符數組參數一個子數組的字符
6. public String(String original):
初始化一個新創建的 String 對象,使其表示一個與參數相同的字符序列;換句話說,新創建的字符串是該參數字符串的副本
例:
1 //空構造 2 String s1 = new String(); 3 System.out.println("s1"+s1);//s1 4 //將字節數組轉成字符串 5 byte[] bys = {97,98,99,100,101}; 6 String s2 = new String(bys); 7 System.out.println("s2:"+s2);//s2:abcde 8 //輸出字符串的長度 9 System.out.println(s2.length());//510 //將字節數組的一部分轉成字符串11 String s3 = new String(bys,1,3);12 System.out.println("s3:"+s3);//s3:bcd13 //將字符數組轉成字符串14 char[] ch = {'a','b','c','d','e','我'};15 String s4 = new String(ch);16 System.out.println("s4:"+s4);//s4:abcde我17 //將字符數組的一部分轉成字符串18 String s5 = new String(ch,2,4);19 System.out.println("s5:"+s5);//s5:cde我12.06 String的特點
String的特點:一旦被賦值就不能改變
String s = “hello”; s += “world”; s的結果是多少?
String s = “hello”; 在方法區的字符串常量池中創建hello
s += “world”;在方法區的字符串常量池中創建world ,再創建空間拼接helloworld
s的結果為helloworld
12.07 String字面值對象和構造方法創建對象的區別
String s = new String(“hello”) 和 String s = “hello”;的區別?
有區別,String s = new String(“hello”);分別在堆內存與方法區創建2個對象
String s = “hello”;只在方法區創建1個對象
12.08 String面試題看程序寫結果
題1:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String s1 = new String("hello"); 6 String s2 = new String("hello"); 7 System.out.println(s1==s2);//false 8 System.out.println(s1.equals(s2));//true 9 10 String s3 = new String("hello");11 String s4 = "hello";12 System.out.println(s3==s4);//false13 System.out.println(s3.equals(s4));//true14 15 String s5 = "hello";16 String s6 = "hello";17 System.out.println(s5==s6);//true18 System.out.println(s5.equals(s6));//true19 }20 }題2:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 //字符串如果是變量相加,先開空間,再拼接。 6 //字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否則,就創建。 7 String s1 = "hello"; 8 String s2 = "world"; 9 String s3 = "helloworld";10 System.out.println(s3 == s1 + s2);//false11 System.out.println(s3.equals(s1 + s2));//true12 System.out.println(s3 == "hello" + "world");//true13 System.out.println(s3.equals("hello" + "world"));//true14 }15 }12.09 String類的判斷功能
1. public boolean equals(Object anObject):
將此字符串與指定的對象比較
2. public boolean equalsIgnoreCase(String anotherString):
將此 String 與另一個 String 比較,不考慮大小寫
3. public boolean contains(CharSequence s):
當且僅當此字符串包含指定的 char 值序列時,返回 true
4. public boolean startsWith(String prefix):
測試此字符串是否以指定的前綴開始
5. public boolean endsWith(String suffix):
測試此字符串是否以指定的后綴結束
6. public boolean isEmpty():
當且僅當 length()為0時返回 true
例:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 //創建字符串對象 6 String s1 = "helloworld"; 7 String s2 = "Helloworld"; 8 System.out.println("equals:"+s1.equals(s2)); 9 System.out.println("equalsIgnoreCase:"+s1.equalsIgnoreCase(s2));10 System.out.println("contains:"+s1.contains("hello"));11 System.out.println("startsWith:"+s1.startsWith("he"));12 System.out.println("isEmpty:"+s1.isEmpty());13 }14 }運行結果:
equals:falseequalsIgnoreCase:truecontains:truestartsWith:trueisEmpty:false12.10 模擬用戶登錄案例
模擬登錄,給三次機會,并提示還有幾次
分析:
1:定義用戶名和密碼。已存在的。
2:鍵盤錄入用戶名和密碼。
3:比較用戶名和密碼。如果都相同,則登錄成功,如果有一個不同,則登錄失敗。
4:給三次機會,用循環改進,用for循環。
1 import java.util.Scanner; 2 public class Practice 3 { 4 public static void main(String[] args) 5 { 6 //定義用戶名和密碼 7 String username = "admin"; 8 String passworld = "12345"; 9 //鍵盤錄入用戶名和密碼10 Scanner sc = new Scanner(System.in);11 12 for (int i = 0; i < 3; i++) 13 {14 System.out.println("請輸入用戶名:");15 String name = sc.nextLine();16 System.out.println("請輸入密碼:");17 String pwd = sc.nextLine();18 if(name.equals(username) && pwd.equals(passworld))19 {20 System.out.println("登錄成功");21 break;22 }23 else24 {25 if(2 - i == 0)26 {27 System.out.println("賬號被凍結");28 }29 else30 {31 System.out.println("用戶名或密碼錯誤,還有"+(2 - i)+"次機會");32 }33 }34 }35 }36 }12.11 斷點查看模擬用戶登錄案例
12.12 模擬用戶登錄案例增強版加入猜數字游戲
1 import java.util.Scanner; 2 public class Practice 3 { 4 public static void main(String[] args) 5 { 6 //定義用戶名和密碼 7 String username = "admin"; 8 String passworld = "12345"; 9 //鍵盤錄入用戶名和密碼10 Scanner sc = new Scanner(System.in);11 12 for (int i = 0; i < 3; i++) 13 {14 System.out.println("請輸入用戶名:");15 String name = sc.nextLine();16 System.out.println("請輸入密碼:");17 String pwd = sc.nextLine();18 if(name.equals(username) && pwd.equals(passworld))19 {20 System.out.println("登錄成功,開始游戲");21 GuessNumberGame.start();22 break;23 }24 else25 {26 if(2 - i == 0)27 {28 System.out.println("賬號被凍結");29 }30 else31 {32 System.out.println("用戶名或密碼錯誤,還有"+(2 - i)+"次機會");33 }34 }35 }36 }37 }1 import java.util.Scanner; 2 3 public class GuessNumberGame 4 { 5 private GuessNumberGame(){} 6 public static void start() 7 { 8 int num = (int)(Math.random()*100)+1; 9 //記錄猜的次數10 int count = 1;11 Scanner sc = new Scanner(System.in);12 System.out.println("請輸入一個數:");13 int guess = sc.nextInt();14 while(guess != num)15 {16 if(guess > 100 || guess < 1)17 {18 System.out.println("數據只能在1~100之間,請重新輸入:");19 guess = sc.nextInt();20 } 21 else if(guess > num)22 {23 System.out.print("你猜的數"+guess+"大了,");24 count++;25 System.out.println("進行第"+count+"次猜數:");26 guess = sc.nextInt();27 }28 else29 {30 System.out.print("你猜的數"+guess+"小了,");31 count++;32 System.out.println("進行第"+count+"次猜數:");33 guess = sc.nextInt();34 }35 }36 System.out.println("恭喜你,猜對了,用了"+count+"次機會");37 }38 }運行結果:
請輸入用戶名:sd請輸入密碼:ger用戶名或密碼錯誤,還有2次機會請輸入用戶名:admin請輸入密碼:12345登錄成功,開始游戲請輸入一個數:58你猜的數58大了,進行第2次猜數:45你猜的數45大了,進行第3次猜數:23你猜的數23大了,進行第4次猜數:12你猜的數12大了,進行第5次猜數:5恭喜你,猜對了,用了5次機會12.13 斷點查看模擬用戶登錄案例增強版加入猜數字游戲
12.14 String類的獲取功能
1. public int length():
返回此字符串的長度
2. public char charAt(int index):
返回指定索引處的 char 值。索引范圍為從 0 到 length() - 1
3. public int indexOf(int ch):
返回指定字符在此字符串中第一次出現處的索引
4. public int indexOf(String str):
返回指定子字符串在此字符串中第一次出現處的索引
5. public int lastIndexOf(int ch,int fromIndex):
返回指定字符在此字符串中最后一次出現處的索引,從指定的索引處開始進行反向搜索
6. public int indexOf(String str,int fromIndex):
返回指定子字符串在此字符串中第一次出現處的索引,從指定的索引開始
7. public String substring(int beginIndex):
返回一個新的字符串,它是此字符串的一個子字符串
8. public String substring(int beginIndex,int endIndex):
返回一個新字符串,它是此字符串的一個子字符串
例:
1 String s = "helloworld";2 System.out.println("length:"+s.length());3 System.out.println("charAt:"+s.charAt(4));4 System.out.println("indexOf:"+s.indexOf('l'));5 System.out.println("indexOf:"+s.indexOf("owo"));6 System.out.println("substring:"+s.substring(2, 6));運行結果:
length:10charAt:oindexOf:2indexOf:4substring:llow12.15 字符串的遍歷
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String s = "helloworld"; 6 for (int i = 0; i < s.length(); i++) 7 { 8 System.out.print(s.charAt(i)+" "); 9 }10 }11 }運行結果:
h e l l o w o r l d12.16 統計大寫,小寫及數字字符的個數案例
統計一個字符串中大寫字母、小寫字母、數字出現的次數
例:Hello123World 大寫2個小寫8個數字3個
分析:
前提:字符串要存在
1:定義三個統計變量
bigCount=0
smallCount=0
numberCount=0
2:遍歷字符串,得到每一個字符。length()和charAt()結合
3:判斷該字符到底是屬于那種類型的
這道題目的難點就是如何判斷某個字符是大的,還是小的,還是數字的。
char ch = s.charAt(x);
if(ch>='0' && ch<='9') numberCount++
if(ch>='a' && ch<='z') smallCount++
if(ch>='A' && ch<='Z') bigCount++
4:輸出結果
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 //定義一個字符串 6 String s = "Hello123World"; 7 8 //定義三個統計變量 9 int bigCount = 0;10 int smallCount = 0;11 int numberCount = 0;12 13 //遍歷字符串,得到每一個字符。14 for(int x = 0; x<s.length(); x++)15 {16 char ch = s.charAt(x);17 18 //判斷該字符到底是屬于那種類型的19 if(ch >= 'a' && ch <= 'z')20 {21 smallCount++;22 }23 else if(ch >= 'A' && ch <= 'Z')24 {25 bigCount++;26 }27 else if(ch >= '0' && ch <= '9')28 {29 numberCount++;30 }31 }32 //輸出結果33 System.out.println("大寫字母"+bigCount+"個");34 System.out.println("小寫字母"+smallCount+"個");35 System.out.println("數字"+numberCount+"個");36 }37 }運行結果:
大寫字母2個小寫字母8個數字3個12.17 斷點查看統計大寫,小寫及數字字符的個數案例
12.18 String類的轉換功能
1. public byte[] getBytes():
使用平臺的默認字符集將此 String 編碼為 byte 序列,并將結果存儲到一個新的 byte 數組中
2. public char[] toCharArray():
將此字符串轉換為一個新的字符數組
3. public static String valueOf(char[] data):
返回 char 數組參數的字符串表示形式
4. public static String valueOf(long l):
返回 long 參數的字符串表示形式
5. public String toLowerCase():
使用默認語言環境的規則將此 String 中的所有字符都轉換為小寫
6. public String toUpperCase():
使用默認語言環境的規則將此 String 中的所有字符都轉換為大寫
7. public String concat(String str):
將指定字符串連接到此字符串的結尾
例:
1 //定義一個字符串 2 String s = "JavaSE"; 3 byte[] bys = s.getBytes(); 4 System.out.print("getBytes:"); 5 for (int i = 0; i < bys.length; i++) 6 { 7 System.out.print(bys[i]+" "); 8 } 9 System.out.println();10 char[] chs = s.toCharArray();11 System.out.print("toCharArray:");12 for (int i = 0; i < chs.length; i++) 13 {14 System.out.print(chs[i]+" ");15 }16 System.out.println();17 String ss = String.valueOf(chs);18 System.out.println("valueOf:"+ss);運行結果:
getBytes:74 97 118 97 83 69 toCharArray:J a v a S E JavaSE12.19 把字符串的首字母轉大寫其他轉小寫
例:helloWORLD 結果:Helloworld
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 //定義一個字符串 6 String s = "helloWORLD"; 7 String s1 = s.substring(0, 1); 8 String s2 = s.substring(1); 9 String ss = s1.toUpperCase().concat(s2.toLowerCase());10 System.out.println(ss);11 12 //簡化13 String str = s.substring(0, 1).toUpperCase()14 .concat(s.substring(1).toLowerCase());15 System.out.println(str);16 17 }18 }12.20 String類的其他功能
1. public String replace(char oldChar,char newChar):
返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的
2. public String replace(String old,String new)
3. public String trim():返回字符串的副本,忽略前導空白和尾部空白
4. public int compareTo(String anotherString):按字典順序比較兩個字符串
5. public int compareToIgnoreCase(String str):按字典順序比較兩個字符串,不考慮大小寫
如果沒有字符不同的索引位置,則較短字符串的字典順序在較長字符串之前。在這種情況下,compareTo 返回這兩個字符串長度的差,即值:this.length()-anotherString.length()
例:
1 String s1 = "abc"; 2 String s2 = "hijk"; 3 String s3 = "xyz"; 4 String s4 = "hello"; 5 String s5 = "hel"; 6 7 System.out.println(s1.compareTo(s2));//-7 8 System.out.println(s3.compareTo(s1));//23 9 //返回的是這兩個字符串長度的差10 System.out.println(s4.compareTo(s5));//212.21 String類的compareTo()方法的源碼解析
12.22 把int數組拼接字符串的案例
把數組中的數據按照指定個格式拼接成一個字符串例:int[] arr = {1,2,3}; 輸出結果:[1, 2, 3]
1 String s = "["; 2 for (int i = 0; i < arr.length; i++) 3 { 4 if(i == arr.length-1) 5 { 6 s += arr[i]; 7 s += "]"; 8 } 9 else10 {11 s += arr[i];12 s += ", ";13 }14 }15 return s;12.23 把int數組拼接成字符串的案例改進版
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 int [] arr = {12,43,11}; 6 String s = getString(arr); 7 System.out.println(s); 8 } 9 public static String getString(int[] arr)10 {11 String s = "[";12 for (int i = 0; i < arr.length; i++) 13 {14 if(i == arr.length-1)15 {16 s += arr[i];17 s += "]";18 }19 else20 {21 s += arr[i];22 s += ", ";23 }24 }25 return s;26 }27 }12.24 字符串反轉的案例
字符串反轉例:鍵盤錄入"abc" 輸出結果:"cba"
1 import java.util.Scanner; 2 3 public class Practice 4 { 5 public static void main(String[] args) 6 { 7 //定義一個空的字符串 8 String s = " "; 9 Scanner sc = new Scanner(System.in);10 System.out.println("請輸入字符串:");11 String line = sc.nextLine();12 char[] ch = line.toCharArray();13 for (int i = ch.length - 1; i >= 0; i--) 14 {15 s += ch[i];16 }17 System.out.println(s);18 }19 }12.25 在大串中查找小串出現的次數案例思路圖解
統計大串中小串出現的次數
例:在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"中java出現了5次
12.26 在大串中查找小串出現的次數案例代碼實現
12.27 在大串中查找小串出現的次數案例代碼優化
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 String s = "woaijavawozhenaijavawozhendeaijavaw" + 6 "ozhendehenaijavaxinbuxinwoaijavagun"; 7 String key = "java"; 8 int count = 0; 9 int index;10 while((index = s.indexOf(key)) != -1)11 {12 count++;13 s = s.substring(index+key.length());14 }15 System.out.println(count);16 }17 }12.28 斷點查看在大串中查找小串出現的次數案例
新聞熱點
疑難解答