java常用類---Scanner類和String類

1.Scanner類

  • A:Scanner的概述: JDK5以後用於獲取用戶的鍵盤輸入
  • B:Scanner的構造方法原理
    Scanner(InputStream source)
    System類下有一個靜態的字段:
    public static final InputStream in; 標準的輸入流,對應着鍵盤錄入。

1.1Scanner類的hasNextXxx()和nextXxx()方法

  • 基本格式
    hasNextXxx() 判斷下一個是否是某種類型的元素,其中Xxx可以是Int,Double等。
    如果需要判斷是否包含下一個字符串,則可以省略Xxx
public class ScannerDemo3 {
    public static void main(String[] args) {

        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.println("請輸入一個整數");
            //hasXXX 判斷錄入數據的 類型
            if (scanner.hasNextInt()) {
                int i = scanner.nextInt();
                System.out.println(i);
                break;
            } else {
                System.out.println("錄入類型不正確,請重新輸入一個整數");
            }
        }

    }
}

nextXxx() 獲取下一個輸入項。Xxx的含義和上個方法中的Xxx相同

public class ScannerDemo {
    public static void main(String[] args) {
        InputStream in = System.in;
       // in “標準”輸入流。此流已打開並準備提供輸入數據。通常,此流對應於鍵盤輸入
        Scanner scanner = new Scanner(in);
        System.out.println("請錄入一個整數");
        int i = scanner.nextInt();
        System.out.println(i);
        scanner = new Scanner(in); //重寫創建一個對象
        System.out.println("請隨便輸入一段字符串");
        //錄入字符串
        String s = scanner.nextLine();
        System.out.println(s);

        //使用nextLine()方法時,你先錄入整數,在錄入字符串,會導致字符串錄入不進去,你可以再錄入字符串時,重新再創建一個Scanner 對象

    }
}

1.2Scanner獲取數據出現的小問題及解決方案

  • A:兩個常用的方法:
    public int nextInt():獲取一個int類型的值
    public String nextLine():獲取一個String類型的值
    public String next():獲取一個String類型的值
  • B:案例演示
    a:先演示獲取多個int值,多個String值的情況
    b:再演示先獲取int值,然後獲取String值出現問題
    c:問題解決方案
    第一種:先獲取一個數值後,在創建一個新的鍵盤錄入對象獲取字符串。
    第二種:把所有的數據都先按照字符串獲取,然後要什麼,你就對應的轉換爲什麼。(後面講)
public class ScannerDemo2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入一個整數");
        int i = scanner.nextInt();
        System.out.println(i);
        scanner = new Scanner(System.in);
        System.out.println("請錄入一個字符串");
        String s = scanner.nextLine();
       // String s = scanner.next(); 錄入的字符串中間,有空格,空格後面的內容不錄入
        System.out.println(s);
    }
}

2.String類

  • A:什麼是字符串
    字符串是由多個字符組成的一串數據==(字符序列)==
    字符串可以看成是字符數組
  • B:String類的概述
    a:字符串字面值"abc"也可以看成是一個字符串對象。
    b:字符串是常量,一旦被創建,就不能被改變。

2.1String類的構造方法

  • 常見構造方法
    public String():空構造
    public String(String original):把字符串常量值轉成字符串
    public String(byte[] bytes):把字節數組轉成字符串
    public String(byte[] bytes,int index,int length):把字節數組的一部分轉成字符串(index:表示的是從第幾個索引開始, length表示的是長度)
    public String(char[] value):把字符數組轉成字符串
    public String(char[] value,int index,int count):把字符數組的一部分轉成字符串

public int length():返回此字符串的長度。

2.2String的特點一旦被創建就不能改變

  • A:String的特點: 一旦被創建就不能改變 因爲字符串的值是在方法區的常量池中劃分空間 分配地址值的
  • B:案例演示
    a:如何理解這句話
    String s = “hello” ;
    s = “world” + “java”; 問s的結果是多少?
    b:畫內存圖解釋: 內容不能變,引用可以變

在這裏插入圖片描述

2.3String類的常見面試題

  • A:面試題1
    "=="和equals()的區別?
    == 號可以比較基本數據類型,也可以比較引用數據類型
    equals方法只能比較引用數據類型,默認比較的是地址值,如果我們想要建立自己的比較方式,我們就需要複寫equals方法
  • B:面試題2
    看程序寫結果
	public class MyTest3 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));

        String s3 = new String("hello");
        String s4 = "hello";
        System.out.println(s3 == s4);
        System.out.println(s3.equals(s4));

        String s5 = "hello";
        String s6 = "hello";
        System.out.println(s5 == s6);
        System.out.println(s5.equals(s6));
    }
}
/*
結果:
false
true
false
true
true
true
*/

2.4String類的判斷功能

public boolean equals(Object obj): 比較字符串的內容是否相同,區分大小寫
public boolean equalsIgnoreCase(String str): 比較字符串的內容是否相同,忽略大小寫
public boolean contains(String str): 判斷字符串中是否包含傳遞進來的字符串
public boolean startsWith(String str): 判斷字符串是否以傳遞進來的字符串開頭
public boolean endsWith(String str): 判斷字符串是否以傳遞進來的字符串結尾
public boolean isEmpty(): 判斷字符串的內容是否爲空串""。

public class MyTest {
    public static void main(String[] args) {
        //與判斷相關的方法
        boolean b = "abc".equals("abc"); //區分大小寫
        System.out.println(b);
        boolean b1 = "ABC".equalsIgnoreCase("abc");//不區分大小寫
        System.out.println(b1);
        //判斷一個字符串中是否包含這個子串
        boolean b2 = "完後餘生,洗衣是你,做飯是你,帶娃還是你".contains("是你");
        System.out.println(b2);

        //判斷是否以這個字符串開頭或結尾
        System.out.println("abc".startsWith("a"));
        System.out.println("abc".endsWith("c"));

        //判斷是否是空串
        System.out.println("".isEmpty());
        System.out.println("".length() == 0);


    }
}

2.5常見對象☞模擬用戶登錄

public class MyTest2 {
    public static void main(String[] args) {
       /* A:
        案例演示:
        需求:模擬登錄, 給三次機會, 並提示還有幾次。
        */

        //模擬從數據庫查出來的數據
        String name = "張三";
        String password = "123456";


        //給三次機會 ,提示剩餘次數
        for (int i = 1; i <= 3; i++) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("請輸入你的用戶名");
            String uname = scanner.nextLine();

            System.out.println("請輸入你的密碼");
            String pwd = scanner.nextLine();
            if (uname.equals(name) && pwd.equals(password)) {
                System.out.println("登錄成功");
                //取款
                break;
            } else {
                if ((3 - i) == 0) {
                    System.out.println("3次機會已經用完,你的卡已被回收.");

                } else {
                    System.out.println("用戶名或密碼輸入錯誤,請重新輸入,你還剩餘" + (3 - i) + "次機會");
                }

            }
        }



    }
}

2.6String類的獲取功能

public int length(): 獲取字符串的長度。
public char charAt(int index): 獲取指定索引位置的字符
public int indexOf(int ch): 返回指定字符在此字符串中第一次出現處的索引。
public int indexOf(String str): 返回指定字符串在此字符串中第一次出現處的索引。
public int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置後第一次出現處的索引。
public int indexOf(String str,int fromIndex): 返回指定字符串在此字符串中從指定位置後第一次出現處的索引。
可以順帶提一下lastIndexOf系列
public String substring(int start): 從指定位置開始截取字符串,默認到末尾。
public String substring(int start,int end): 從指定位置開始到指定位置結束截取字符串。

public class MyTest2 {
    public static void main(String[] args) {
        //有關於獲取的方法
        int length = "這是一個字符串".length(); //獲取長度


        //字符串編有索引
        //indexOf() 查找該字符或字符串,在原串中第一次出現的索引
        int index = "這是一個字符串是".indexOf('是');
        //如果沒有找到 返回 -1 我們經常用這個作爲判斷依據
        index = "這是一個字符串是".indexOf("字符串2");

        System.out.println(index);
        //charAt(6) 根據索引截取單個字符
        char ch = "這是一個字符串是".charAt(6);
        System.out.println(ch);
        String s = "這是一是個是字符是串是";

        ch = s.charAt(s.indexOf("字"));

        System.out.println(ch);

        //從後往前檢索
        int index1 = s.lastIndexOf("是");
        System.out.println(index1);
        //可以指定開始的地方來檢索

        int index2 = s.indexOf('是', s.indexOf('個'));
        System.out.println(index2);

        //從原串中截取一段字串

        String str = "假如我年少有爲不自卑,懂得什麼是珍貴";
        //根據起始索引截取到末尾
        String s1 = str.substring(str.indexOf("懂"));
        System.out.println(s1);

        //根據首尾索引,截取一部分字符串
        String s2 = str.substring(3, str.indexOf('卑')+1); //含頭不含尾部
        System.out.println(s2);
    }
}

2.7字符串的遍歷

public class MyTest3 {
    public static void main(String[] args) {
        String str = "假如我年少有爲不自卑,懂得什麼是珍貴";
       // char c = str.charAt(0);
        //遍歷字符串
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            System.out.println(c);
        }

    }
}

2.8統計不同類型字符個數

public class MyTest4 {
    public static void main(String[] args) {
        /*A:
        案例演示:
        需求:統計一個字符串中大寫字母字符,小寫字母字符,數字字符出現的次數。(不考慮其他字符)*/
        String str="asfdassdfASFSsf1222asdfas5555s4555AFFDDdddaAAA";
        //遍歷字符串
        int num=0;
        int da=0;
        int xiao=0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if(ch>='a'&&ch<='z'){
                xiao++;
            }else if(ch >= 'A' && ch <= 'Z'){
                da++;
            } else{
                num++;
            }
        }

        System.out.println("大寫字母"+da+"個");
        System.out.println("小寫字母" +xiao+ "個");
        System.out.println("數字字符" + num + "個");

    }
}

2.9String類的轉換功能

public byte[] getBytes(): 把字符串轉換爲字節數組。
public char[] toCharArray(): 把字符串轉換爲字符數組。
public static String valueOf(char[] chs): 把字符數組轉成字符串。
public static String valueOf(int i): 把int類型的數據轉成字符串。
注意:String類的valueOf方法可以把任意類型的數據轉成字符串。
public String toLowerCase(): 把字符串轉成小寫。
public String toUpperCase(): 把字符串轉成大寫。
public String concat(String str): 把字符串拼接。

public class MyTest {
    public static void main(String[] args) {
        //轉換功能相關的方法
        //轉換大小寫
        String s = "abcd".toUpperCase();
        System.out.println(s);
        String s1 = "AAAA".toLowerCase();
        System.out.println(s1);

        //把字符串轉換成字節數組
        byte[] bytes = "abcd".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        System.out.println(bytes.length);
        //把字節數組轉換成字符串
        String s2 = new String(bytes, 0, bytes.length);
        System.out.println(s2);

        System.out.println("-----------------------------");
        //把字符串轉換成字節數組
        byte[] bytes1 = "我在人民廣場喫着炸雞".getBytes();
        System.out.println(bytes1.length);//
        for (int i = 0; i < bytes1.length; i++) {
            System.out.println(bytes1[i]);
        }
        //把字節數組轉換成字符串
        String s3 = new String(bytes1, 6, 15);
        System.out.println(s3);

        //UTF-8 一個漢字佔3個字節

       // System.out.println("錒".getBytes().length);

        //把字符串轉換成字符數組
        String s4="我在人民廣場喫着炸雞";
        /*
        char[] chars = new char[s4.length()];
        for (int i = 0; i < s4.length(); i++) {
            chars[i]=s4.charAt(i);
        }

         */

        char[] chars = s4.toCharArray();

        //把一個字符數組轉換成字符串
        String s5 = new String(chars);
        System.out.println(s5);

        String concat = "abc".concat("aaa").concat("ccc").concat("dddd");
        System.out.println(concat);


    }
}

2.10按要求轉換字符

需求:把一個字符串的首字母轉成大寫,其餘爲小寫。(只考慮英文大小寫字母字符)

public class MyTest2 {
    public static void main(String[] args) {
     /*   A:
        案例演示:
        需求:把一個字符串的首字母轉成大寫,其餘爲小寫。(只考慮英文大小寫字母字符)*/
        String s = "caBDfdaaffdfeadfeafdFAAFF";
        //鏈式編程
        String concat = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
        System.out.println(concat);

        char ch='A'+32;  //
        System.out.println(ch);

    }
}

2.11String類的其他功能

  • A:String的替換功能及案例演示
    public String replace(char old,char new) 將指定字符進行互換
    public String replace(String old,String new) 將指定字符串進行互換
  • B:String的去除字符串兩空格及案例演示
    public String trim() 去除兩端空格
public class MyTest {
    public static void main(String[] args) {
        String str="奧巴馬和特朗普是美國總統";
        //一次替換一個字符
        String s = str.replace('奧', '*');
        System.out.println(s);

        String s1 = str.replace("奧巴馬", "***");
        System.out.println(s1);

        String s2 = str.replace("奧巴馬", "***").replace("特朗普", "####");
        System.out.println(s2);
        //去除兩端空格
        String username="     zhangsan     ";
        String s3 = username.trim();
        System.out.println(s3);
    }
}
  • C:String的按字典順序比較兩個字符串及案例演示
    public int compareTo(String str) 會對照ASCII 碼錶 從第一個字母進行減法運算 返回的就是這個減法的結果
    如果前面幾個字母一樣會根據兩個字符串的長度進行減法運算返回的就是這個減法的結果
    如果連個字符串一摸一樣 返回的就是0
    public int compareToIgnoreCase(String str) 跟上面一樣 只是忽略大小寫的比較
public class MyTest2 {
    public static void main(String[] args) {
        String str="abc";
        String str2="abcdef";
        boolean b = str.equals(str2);
       // str.equalsIgnoreCase(str) 不區分大小寫的比較

        //比較兩個字符串 按照字典順序去比,返回的是兩個字符的差值
        //當字典順序比不出來,用長度去比
        int num = str.compareTo(str2);
        if(num==0){

        }

      //  str.compareToIgnoreCase(str2) 不區分大小寫的比較
        System.out.println(num);
    }
}

2.12把數組轉成字符串

public class MyTest3 {
    public static void main(String[] args) {
       /* A:
        案例演示
        需求:把數組中的數據按照指定個格式拼接成一個字符串
        舉例:
        int[] arr = {1, 2, 3};
        拼接結果:
        "[1, 2, 3]"*/

        int[] arr = {1, 2, 3,4,5};
        //對上面的數組,進行遍歷,經過你的處理得到一個漂亮的字符串
        //"[1,2,3]";
        String str="[";
        for (int i = 0; i < arr.length; i++) {
            if(i==arr.length-1){
                str+=arr[i]+"]";
            }else{
                str+=arr[i]+",";
            }
        }
        System.out.println(str);
    }
}

2.13字符串反轉

public class MyTest {
    public static void main(String[] args) {
        /*A:
        案例演示
        需求:把字符串反轉
        舉例:鍵盤錄入 "abc"
        反轉結果:"cba"*/
        Scanner scanner = new Scanner(System.in);
        System.out.println("請隨便輸入一段字符串");
        String s = scanner.nextLine(); //你愛我
        String str="";
        for (int i = s.length()-1; i >=0; i--) {
            char c = s.charAt(i);
            str+=c;
        }
        System.out.println(str);
    }
}

2.14在大串中查找小串出現的次數

需求:統計大串中小串出現的次數
舉例: "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun”中java出現了5次

	public class MyTest2 {
    public static void main(String[] args) {
        String maxStr = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";
        //其他辦法
        //替換:把java替換成一個特殊字符,統計這個特殊字符
        int count=0;
        if(!maxStr.contains("#")){
            String string = maxStr.replace("java", "#");
            for (int i = 0; i < string.length(); i++) {
                char c = string.charAt(i);
                if(c=='#'){
                    count++;
                }
            }
        }

        System.out.println("java出現了" + count + "次");

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章