Java的語句類型、字符轉換及字符串用法


If語句、switch語句、for循環語句:

    if...

      if...else...

      if...else if...

      if...else if...else...

      switch...case...default(可以省略)...

      (既然有了if, 為什么還要有switch)

      switch是對值的比較(數字, 字符串)

 

值0是什么類型, case后面的值就要是什么類型

      switch(值0) {

           case 值1:

                 執行語句

                 break;

           case 值1:

                 執行語句

                 break;

           default:

                 執行語句

                 break;

      }

      for(初始值;條件判斷;初始值改變) { 執行語句}

      for(int i=0;i<5;i++)

 

      foreach String[] str = ...

           for(String s : str)

      break;

           終止循環

      continue;

           退出本次循環, 繼續下次循環

 

while(條件) {  }

do{}while()         ←先執行do里的內容再去判斷,至少執行一次

 

類型轉換:

double float long int char short byte

      char short byte進行運算的時候, 取值默認為int

      隱式轉換(我們看不到轉換的過程)

      條件:

      由低精度向高精度轉換沒問題,高精度向低精度轉換,可能會造成數字丟失

           double   16     1.22222222222

           float       8       1.2222222

      double>float>long>int>short>byte

      顯式轉換(高精度向低精度轉換)

 

定義一個字符串

           String str = new String(c);

System.out.println(str);  ←輸出這個字符串

輸出一個字符串的長度.length()

           System.out.println(str.length());

字符串索引查找.indexOf()  里面傳一個參數,會找這個字符串第一次出現的索引值

           System.out.println(str.indexOf("a"));

 

           .lastIndexOf() 里面傳一個參數,會找字符串最后一次出現的索引值

           System.out.println(str.lastIndexOf("a"));

 

判斷字符串是否以括號內內容為開頭的.startWith()

           System.out.println(str.startWith("a"));

判斷字符串是否以括號內內容結尾的.endWith()

           System.out.println(str.endWith("a"));

 

 

字符串截取.substring(5)  單個參數,截取從括號內索引值往后的字符串

           String s1 = str.substring(5);

             .substring(2,4)  兩個參數,截取從前一個索引值開始的內容到后面索

引值-1索引值的內容,最后一個索引值本身不包括。

           String s2 = str.substring(2,4);//不包括4

去空格方法.trim()    只去掉前面和后面的空格, 中間的不管

String str11 = "   its a new world, its a new start   ";

      System.out.println(str11.trim());

字符串替換方法.replace()里面傳兩個參數,可以都是''字符,也可以都是""字符串,把前面的一樣的參數全部換成后面的參數

      System.out.println(str11.trim().replace("i","_"));

      System.out.println(str11.trim().replace('t','+'));

 

正則表達式的替換.replaceAll(參數1,參數2)    (\\s是空格)

      System.out.println(str11.trim().replaceAll("\\s","6"));  ←把(\\s)空格換成6

 

☆判斷字符串的值,比較是否相等(值1.equals(值2))

      String ss1 = "abc";

      String ss2 = "def";

      System.out.println(ss1.equals(ss2));

 

大寫轉換.toUpperCase()

小寫轉換.toLowerCase()

數組賦值的兩種方法:

           int[] a1 = new int [] {3,4,6,2,8};

           int[] a2 = {3,4,6,2,8};

數組的排序(快速排序)

           Arrays.sort(a1);

           System.out.println(Arrays.toString(a1));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM