標籤:
1:Scanner的使用(瞭解)
(1)在JDK5以後出現的用於鍵盤錄入資料的類。
(2)構造方法:
A:講解了System.in這個東西。
它其實是標準的輸入資料流,對應於鍵盤錄入
B:構造方法
InputStream is = System.in;
Scanner(InputStream is)
C:常用的格式
Scanner sc = new Scanner(System.in);
(3)基本方法格式:
A:hasNextXxx() 判斷是否是某種類型的
B:nextXxx() 返回某種類型的元素
(4)要掌握的兩個方法
A:public int nextInt()
B:public String nextLine()
(5)需要注意的小問題
A:同一個Scanner對象,先擷取數值,再擷取字串會出現一個小問題。
B:解決方案:
a:重新定義一個Scanner對象
b:把所有的資料都用字串擷取,然後再進行相應的轉換
2:String類的概述和使用(掌握)
(1)多個字元組成的一串資料。
其實它可以和字元數組進行相互轉換。
(2)構造方法:
A:public String()
B:public String(byte[] bytes)
C:public String(byte[] bytes,int offset,int length)
D:public String(char[] value)
E:public String(char[] value,int offset,int count)
F:public String(String original)
下面的這一個雖然不是構造方法,但是結果也是一個字串對象
G:String s = "hello";
(3)字串的特點
A:字串一旦被賦值,就不能改變。
注意:這裡指的是字串的內容不能改變,而不是引用不能改變。
B:字面值作為字串對象和通過構造方法建立對象的不同
String s = new String("hello");和String s = "hello"的區別?
一個是在堆上建立,一個是在方法區的常量區建立。
其中String s = new String("hello")是在堆上建立,再建立的過程中,回去方法區尋找“hello”的存在,若存在即返回對應的記憶體位址給堆上的對象。若不存在就建立,再返回建立後的地址值。
String s = "hello"是直接去尋找方法區,若存在就返回地址值給s,若不存在,則建立後再返回。
(4)字串的面試題(看程式寫結果)
注意: “==”比較的是對象的地址值,equals是object類中的方法,預設比較的也是地址值,一般情況下,子類都會重寫equals方法。
A:==和equals()
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
B:字串的拼接
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
(5)字串的功能(自己補齊方法中文意思)
A:判斷功能
boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
boolean contains(String str)
boolean startsWith(String str)
boolean endsWith(String str)
boolean isEmpty()
B:擷取功能(查詢功能)
int length()
char charAt(int index)
int indexOf(int ch)
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)
C:轉換功能
byte[] getBytes()
char[] toCharArray()
static String valueOf(char[] chs)
static String valueOf(int i)
String toLowerCase()
String toUpperCase()
String concat(String str)
D:其他功能
a:替換功能
String replace(char old,char new)
String replace(String old,String new)
b:去空格功能
String trim()
c:按字典比較功能
int compareTo(String str)
int compareToIgnoreCase(String str)
(6)字串的案例
A:類比使用者登入
B:字串遍曆
C:統計字串中大寫,小寫及數字字元的個數
D:把字串的首字母轉成大寫,其他小寫
E:把int數組拼接成一個指定格式的字串
F:字串反轉
G:統計大串中小串出現的次數
Java中的Scanner類和String類