日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java --- 基础学习Ⅰ

發布時間:2023/12/10 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java --- 基础学习Ⅰ 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第一章 開發前言

位、字節

  • 位(bit): 一個數字0或一個數字1,代表一位

  • 字節(Byte): 每逢8位是一個字節,這時數據存儲的最小單位

1 Byte = 8 bit

1 KB = 1024 Byte

1 MB = 1024 KB

1 GB = 1024 MB

1 TB = 1024 GB

1 PB = 1024 TB

MS-DOS(Microsoft Disk Operating System)

第二章 Java語言開發環境搭建

2.1 Java虛擬機–JVM

  • JVM(Java Virtual Machine): Java虛擬機,簡稱JVM,是運行所有Java程序的假想計算機,是Java程序的運行環境,是Java最具吸引力的特性之一。我們編寫的Java代碼, 都運行在JVM之上
  • 跨平臺: 任何軟件的運行,都必須要運行在操作系統之上,而我們使用Java編寫的軟件可以運行在任何的操作系統上,這個特性成為Java語言的跨平臺性。該特性是由JVM實現的,我們編寫的程序運行在JVM上,而JVM運行在操作系統上
Java程序Windows下的JVMLinux下的JVMMac下的JVM

如圖所示,Java的虛擬機本身不具備跨平臺功能的,每個操作系統下都有不同版本的虛擬機

2.2 JRE和JDK

  • JRE(Java Runtime Environment): 是Java程序的運行時環境,保護JVM和運行時所需要的核心類庫
  • JDK(Java Development Kit): 是Java程序開發工具包,保護jre和開發人員使用的工具

我們想運行已有的Java程序,那么只需安裝JRE即可

我們想開發一個全新的Java程序,那么必須安裝JDK

JRE = “運行類庫” + “JVM”

JDK = “編譯器等開發工具” + JRE

2.3 安裝步驟

  • 下載Java JDK 11 Windows 11.0.5

2.4 目錄說明

安裝好Java之后,在安裝路徑D:\develop\Java\會生成一些文件夾.下面說明各個文件夾的作用:

  • bin: 存放了JDK的各種工具命令。(javac和java就放在這個目錄)
  • conf: 存放了JDK的相關配置文件
  • include: 存放了一些平臺特定的頭文件
  • jmods: 該路徑下存放了JDK的各種模塊
  • legal: 存放了JDK各模塊的授權文檔
  • lib: 存放路JDK工具的一些補充JAD包

第三章 常見語法

1 常用DOS命令

操作說明
盤符名稱盤符切換。 E: 回車,表示切換到E盤
dir查看當前路徑下的內容
cd 目錄進入單級目錄. cd marron
cd…回退到上一級
cd 目錄1\目錄2\ …進入多級目錄: cd itheima\JavaSE
cls清屏幕
exit退出命令提示符窗口

2 path 環境變量的配置

開發Java程序,需要使用JDK提供的開發工具,而這些工具在JDK的安裝目錄的bin目錄下.

為了在開發Java程序的時候,能夠方便的使用javac和java這些命令,我們需要配置Path環境變量

3. HelloWorld案例

3.1 Java程序開發運行流程

開發Java程序,需要三個步驟: 編寫程序,編譯程序,運行程序

3.2 Hello World案例的編寫

  • 新建文本文檔文件,修改為HelloWorld.java
  • 用記事本打開HelloWorld.java文件,書寫程序內容
  • public class HelloWorld{public static void main(String[] args){System.out.println('HelloWorld')} }
    • 編譯
    $ javac HelloWorld.java
    • 運行
    $ java HelloWolrd

    4. 略

    5. Notepad軟件的安裝和使用(略)

    6. 注釋(略)

    • 單行注釋: //
    • 多行注釋: /**/
    • 文檔注釋: /** */

    7. 關鍵字

    • 關鍵字的特定:

      • 關鍵字的字母全部是小寫

      • 常用的代碼編輯器,針對關鍵字有特殊的顏色標記,非常直觀

        • public class HelloWolrd{/*這是main方法main方法是程序的入口方法,代碼的執行是從main方法開始的*/public static void main(String[] args){System.out.println('marron')} }

    8. 常量

    • 常量的概述: 在程序運行過程中,其值不可以發生改變的量

    • 常量的分類:

      • 常量類型說明舉例
        字符串常用雙引號括起來的內容“HelloWorld”
        整數常量不帶小數的數字666,-88
        小數常量帶小數的數字13.14,-5.21
        字符常量用單引號括起來的內容‘A’,‘0’,’,‘我’
        布爾常量布爾值,表示真假只有兩個值: true, false
        空常量一個特殊的值,空值值是null

    9. 數據類型

    • 計算機的存儲單元: 我們知道就算機是可以用來存儲數據的,但是無論是內存還是硬盤,計算機設備的最小信息單元叫"位(bit)",我們又稱之為"比特位",通常用小寫的字母"b"表示。而計算機中最小的存儲單元叫"字節(byte)",通常用大寫字母"B"表示,字節是由連續的8個位組成

    • Java語言是強語言類型,對于每一種數據都給出了明確的數據類型,不同的數據類型也分配了不同的內存空間,所以它們表示的數據大小也是不一樣的.

      • 數據類型:
        • 基本數據類型:
          • 數值型:
            • 整數(byte,short,int,long)
            • 浮點數(float, double)
            • 字符(char)
          • 非數值型
        • 引用數據類型:
          • 類(class)
          • 接口(interface)
          • 數組([])
    • 數據類型內存占用和取值范圍

    數據類型關鍵字內存占用取值范圍
    整數byte1-128~127
    整數short2-32768~32767
    整數int4-2^31 ~ 2^31 -1
    整數long8-2^63 ~ 2^63 -1
    浮點數float4負數: -3.402823E + 38 ~ -1.401298E -45; 正數: 1.401298E - 45 到 3.402823E + 38
    浮點數double8負數: -1.797693E + 308 ~ -4.9000000E - 324; 正數: 4.900000000E - 324 到1797693E + 308
    字符char20~65535
    布爾boolean1true, false

    10. 變量

    • 變量: 在程序運行過程中,其值可以發生改變的量。 從本質上講: 變量是內存中的一小塊區域

    • 格式: 數據類型 變量名 = 變量值; (int a = 10)

    • 變量使用的注意事項:

      • VariableDemo02.java:30: 錯誤: 整數太大: 告訴計算機右邊的值是long類型即可
    long l = 10000000000L;
    • VariableDemo02.java:35: 錯誤: 不兼容的類型: 從double轉換到float可能會有損失: 告訴計算機右邊的是float類型即可
    float f = 13.14F; System.out.println(f);

    11. 標識符

    • 標識符: 就是給類,方法,變量等起名字的符號
    • 標識符定義規則:
      • 數字、字母、下劃線(_)和美元符($)組成
      • 不能以數字開頭
      • 不能是關鍵字
      • 區分關鍵字
    • 常見命名約定:
      • 小駝峰命名法:
        • 標識符是一個單詞的時候,首字母開頭小寫, name
        • 標識符是多個單詞時,第一個字母開頭小寫,其他單詞首字母大寫, firstName
      • 大駝峰命名法:
        • 標識符是一個單詞的時候,首字母開頭大寫, Student
        • 標識符是多個單詞時,每個單詞首字母大寫, GoodStudent

    12. 類型轉換

    • 自帶類型轉換:
      • 把一個數據范圍小的數值或者變量賦值給另一個表示數據范圍大的變量: double d = 10
      • 下面是表示數據范圍從小到大圖
    byteshortcharintlongfloatdouble
    • 常見報錯:

      • ConversionDemo.java:15: 錯誤: 不兼容的類型: 從byte轉換到char可能會有損失: byte無法轉換位char
    • 強制類型轉換: 把一個表示數據范圍大的數值或者變量賦值給另一個表示數據范圍小的變量

      • 格式: 目標數據類型 變量名 = (目標數據類型)值或者變量
        • int k = (int)88.88
        • ConversionDemo.java:18: 錯誤: 不兼容的類型: 從double轉換到int可能會有損失: int k = 88.88

    13. 運算符

    • 運算符: 對常量或者變量進行操作的符號

    • 表達式: 用運算符把常量或者變量連接起來符合java語法的式子就可以成為表達式.不同運算符連接的表達式體現的是不同類型的表達式.

    • 舉例子:

      • int a = 10; int b = 20; int c = a + b;
      • +: 是運算符,并且是算數運算符

      • a+b: 是表達式,由于+是算術運算符,所以這個表達式叫算數表達式

    字符的"+"操作

    拿字符在計算機底層對應的數值來進行計算的

    • ‘A’ -> 65 (A-Z是連續的)
    • ‘a’ -> 97 (a-z是連續的)
    • ‘0’ -> 48 (0-9是連續的)

    算數表達式中包含多個基本數據類型的值的時候,整個算數表達式的類型會自動進行提升,提升規則:

    • byte類型,short類型和char類型將被提升到int類型
    • 整個表達式的類型自動提升到表達式中最高等級操作數同樣的類型,
      • 等級順序: byte,short,char -> int -> ling -> float -> double

    [報錯]:

    OperatorDemo02.java:13: 錯誤: 不兼容的類型: 從int轉換到char可能會有損失:

    public class OperatorDemo02{public static void main(String[] args){int i = 10;char c = 'A';char ch = i + c;System.out.println(ch)} }

    字符串的"+"操作

    public class OperatorDemo03{public static void main(String[] args){System.out.println("Marron" + "Hao"); // MarronHaoSystem.out.println("Marron" + 666); // Marron666System.out.println(666 + "Marron"); // 666MarronSystem.out.println("Marron" + 6 + 66); // Marron666System.out.println(1+ 99 + "年Marron"); // 100年Marron} }

    當"+“操作中出現字符串時,這個”+"是字符串連接符,而不是算數運算符

    賦值運算符

    符號作用說明
    =賦值a=10, 將10賦值給變量a
    +=加后賦值a+=b, 將a+b的值給a
    -=減后賦值a+=b, 將a-b的值給a
    *=乘后賦值a*=b, 將a*b的值給a
    /=除后賦值a/=b, 將a?b的商給a
    %=取余后賦值a%=b, 將a?b的余數給a
    public class OperatorDemo{public static void main(String[] args){// 把10賦值給int類型的變量i;int i = 10;System.out.println("i: " + i);// += 把左邊和右邊的數據做加法操作,結果賦值給左邊i += 20;System.out.println("i: " + i);// 注意: 擴展的賦值運算符底層隱含了強制類型轉換short s = 10;s += 20;System.out.println("s: " + s);} }

    擴展的賦值運算符,隱含了強制類型轉換

    自增自減運算符

    符號作用說明
    ++自增變量的值加1
    自減變量的值減1
    public class OperatorDemo{public static void main(String[] args){// 定義變量int i = 10;System.out.println("i: " + i); // 10i++;System.out.println("i: " + i); // 11} }

    關系運算符

    符號說明
    ==a==b, 判斷a和b的值是否相等,成立為true,不成立為false
    !=a!=b, 判斷a和b的值是否不相等,成立為true,不成立為false
    >a>b, 判斷a是否大于b,成立為true,不成立為false
    >=a>=b, 判斷a是否大于或等于b,成立為true,不成立為false
    <a<b, 判斷a是否小于b,成立為true,不成立為false
    <=a<=b, 判斷a是否小于或等于b,成立為true,不成立為false

    邏輯運算符

    符號作用說明
    &邏輯與a&b, a和b都是true,結果為true,否則為false
    |邏輯或a|b, a和b都是false,結果為false,否則為true
    ^邏輯異或a^b, a和b不同為true,否則為false
    !邏輯非!a, a為true時,結果為false;a為false時,結果為true
    /*邏輯運算符 */ public class OperatorDemo01{public static void main(String[] args){// 定義變量int i = 10;int j = 20;int k = 30;// & 有false則falseSystem.out.println( (i>j) & (i>k)); // false & false} }

    [短路邏輯運算符]

    符號作用說明
    &&短路與作用與&相同,但有短路效果
    ||短路或作用與|相同,但有短路效果

    注意事項:

    • 邏輯運算符,左右兩邊必然執行
    • 短路運算符,只有當前提條件滿足了后面的才執行.

    三元運算符

    • 格式: 關系表達式? 表達式1 : 表達式2

    【案例1】: 動物園里有兩只老虎,已知兩只老虎的體重分別為180kg、200kg,請用程序實現判斷兩只老虎的體重是否相同.

    public class OperatorTest01{public static void main(String[] args){int weight = 180;int weight = 200;boolean b = weight1 == weight2? true: false;System.out.println("b: " + b);} }

    【案例2】: 一座寺廟里住著三個和尚,已知他們的身高分別為150cm、210cm、165cm,請用程序實現獲取者三個和尚的最高身高

    public class OperatorTest02{public static void main(String[] args){int height1 = 150;int height2 = 210;int height3 = 165;int max1 = height1 > height2 ? height1 : height2;int max = max1 > height3 ? max1 : height3;System.out.println("max: " + max);} }

    14. 數據輸入

    scanner使用的基本步驟

    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);} }

    【栗子1】: 一個寺廟住著三個和尚,他們的身高必須經過測量得出,請用程序實現獲取這三個和尚的最高身高

    import java.util.Scanner;public class ScannerTest{public static void main(String[] args){Scanner sc = new Scanner(System.in);int height1 = sc.nextInt();int height2 = sc.nextInt();int height3 = sc.nextInt();int tmpHeight = height1 > height2 ? height1 : height2;int maxHeight = tmpHeight > height3 ? tmpHeight : height3;System.out.println("maxHeight: " + maxHeight);} }

    15. 分支語句

    順序結構

    順序結構: 是程序中最簡單最基本的流程控制,沒有特定的語法結構,按照代碼的先后順序,依次執行,程序中大多數的代碼都是這樣執行的

    /*順序結構 */ public class OrderDemo {public static void main(String[] args){System.out.println("開始");System.out.println("語句A");System.out.println("語句B");System.out.println("語句C");System.out.println("結束");} }

    if 語句

    • if語句格式1:
    /*格式:if(關系表達式){語句體;} */

    執行流程:

  • 首先巨酸關系表達式的值
  • 如果關系表達式的值為true就執行語句體
  • 如果關系表達式的值為false就不執行語句體
  • 繼續執行后面的語句內容
  • public class IfDemo{public static void main(String[] args){System.out.println("開始");// 定義兩個變量int a = 10;int b = 20;// 需求: 判斷a和b的值是否相等,如果相等,就在控制臺輸出: a等于b if(a == b){System.out.println("a等于b");}// 需求: 判斷a和c的值是否相等,如果相等,就在控制臺輸出: a等于cif(a == c) {System.out.println("a等于c");}System.out.println("結束");} }
    • if語句格式2:
    /*格式:if(關系表達式){語句體1;} else {語句體2;} */

    需求: 判斷輸入的a是否大于b.是在控制臺輸出"a大于b",否則輸出"a不大于b"

    import java.util.Scanner; public class IfDemo02{public static void main (String[] args){System.out.println("開始");Scanner sc = new Scanner(System.in);int a = sc.nextInt();int b = sc.nextInt();if(a > b){System.out.println("a大于b")} else {System.out.println("a不大于b")}System.out.println("結束");} }

    需求: 任意給出一個整數,請用程序實現判斷該整數是奇數還是偶數,并在控制臺輸出該整數是奇數還是偶數.

    import java.util.Scanner; public class IfDemo03{public static void main(String[] args){System.out.println("開始");Scanner sc = new Scanner(System.in);int num = sc.nextInt();if(num % 2 == 0){System.out.println("您輸入的是偶數");} else {System.out.println("您輸入的是奇數");}System.out.println("結束"); } }
    • if語句格式2:
    /*格式:if(關系表達式1){語句體1;} else if(關系表達式2){語句體2;}...else {語句體n+1;} */

    需求: 輸入整數17,輸出星期一星期天

    import java.util.Scanner; public class IfDemo04{public static void main(String[] args){System.out.println("開始");Scanner sc = new Scanner(System.in);System.out.println("請輸入一個星期數(1-7)");int day = sc.nextInt();if(day == 1){System.out.println("星期一");} else if (day == 2) {System.out.println("星期二");} else if (day == 3) {System.out.println("星期三");} else if (day == 4) {System.out.println("星期四");} else if (day == 5) {System.out.println("星期五");} else if (day == 6) {System.out.println("星期六");} else if (day == 7) {System.out.println("星期天");}System.out.println("結束");} }

    switch語句

    /*格式switch(表達式){case 值1:語句體1;break;case 值2:語句體2;break;...default:語句體n+1;[break;]} */

    需求: 一年有12個月,分別屬于春夏秋冬4個季節,鍵盤錄入一個月份,請用程序實現判斷該月份屬于哪個季節,并輸出

    import java.util.Scanner; public class SwitchTest{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("請輸入一個月份: ");int month = sc.nextInt();switch(month){case 12:case 1:case 2:System.out.println("冬季");break;case 3:case 4:case 5:System.out.println("春季");break;case 6:case 7:case 8:System.out.println("夏季");break;case 9:case 10:case 11:System.out.println("秋季");break;default:System.out.println("您輸入的月份錯誤");break;}} }

    16. 循環語句

    for 循環語句

    /*格式;for(初始化語句; 條件判斷語句; 條件控制語句){循環體語句;} */

    需求1: 輸出5次"HelloWorld"

    public class ForDemo{public static void main(String[] args){for(int i = 0; i < 5; i++){System.out.println("HelloWorld");}} }

    需求2: 在控制臺輸出所有的"水仙花數"

    public class ForTest{public static void main (String[] args){for(int i = 100; i <=999; i++){// 個位int units = i % 10;// 十位int tens = (i /10) % 10;// 百位int hundreds = i / 10/10 % 10;if(i == units * units * units + tens * tens * tens + hundreds * hundreds *hundreds ){System.out.println(i);}} } }

    while 循環語句

    /*格式:while(條件判斷語句){循環體語句;條件控制語句;} */

    需求: 世界最高山峰珠穆朗瑪峰(8844.43米 = 8844430毫米), 假如我有一張足夠大的紙,它的初始厚度是0.1毫米.請問,折疊多少次,可以超過珠穆朗瑪峰的高度?

    public class whileTest{public static void main(String[] args){double maxHeight = 8844430;double tmpHeight = 0.1;int count = 0;while(tmpHeight < maxHeight && count < 9999){tmpHeight *= 2;count++;}System.out.println("折疊: " + count + "次后,高度為: " + tmpHeight);} }

    do…while循環語句

    /*基本格式:do{循環體語句;} while(條件判斷語句); */

    17. 跳轉控制語句

    • continue: 用在循環中,基于條件控制,跳過某次循環體內容的執行,繼續下次一的執行
    • break: 用在循環體中,基于條件控制,終止循環體內容的執行,也就是說結束當前的整個循環
    public class ControlDemo{public static void main(String[] args){for(int i = 1; i<=5; i++){if(i%2 == 0){continue;// break;}System.out.println(i);}} }

    18. 循環嵌套

    public class ForForDemo{public static void main(String[] args){for(int hour = 0; hour<24; hour++){for(int minute = 0; minute<60; minute++){System.out.println(hour + "時" + minute + "分");}System.out.println("---------------");}} }

    19. Random

    用于產生一個隨機數

    import java.util.Random; Random r = new Random(); int number = r.nextInt(10); /*產生10個隨機數 */ import java.util.Random; public class RandomDemo{public static void main(String[] args){Random r = new Random();for(int i = 0; i< 10; i++){int number = r.nextInt(10);System.out.println("number: " + number);}// 生成一個 0~100之間的隨機數(包含0, 不包含100)int x = r.nextInt(100);} }

    【栗子】: 猜數字: 使用Random函數生成一個1~100之間的數,然后等待玩家輸入數字.若比生成的大則提示猜大了,若小則提示猜小,否則提示"bingo"

    import java.util.Random; import java.util.Scanner; public class RandomTest{public static void main(String[] args){Random r = new Random();Scanner sc = new Scanner(System.in);// 生成隨機數int num = r.nextInt(100) + 1;while(true){System.out.println("請輸入1~100");int guess = sc.nextInt();if(guess > num) {System.out.println("猜大了");} else if (guess < num){System.out.println("猜小了");} else {System.out.println("恭喜你猜中了");break;}}} }

    第四章 IDEA概述和安裝

    IDEA全稱IntelliJ IDEA是Java語言開發的集成環境,它是業界公認的目前用于Java程序開發最好的工具.

    • 集成環境: 把代碼編寫,編譯,執行,調試等多種功能綜合到一起的開發工具

    • IDEA的下載和安裝:

      • 下載: https://www.jetbrains.com/idea/
      • 安裝: 傻瓜式安裝,建議修改安裝路徑

    IDEA中創建一個項目

  • 創建一個空項目(JavaSE_Code)
  • 創建一個新模塊(idea_test)
  • 在idea_test模塊下的src中創建一個包(com.marron)
  • 在com.marron包下新建一個類(HelloWorld)
  • 在HelloWorld類中編寫代碼
  • 在idea中執行程序
  • IDEA中的項目結構

    • 在IDEA中是以項目為單位管理應用程序的.
    • 一個項目包含多個模塊
    • 一個模塊包含多個包
    • 一個包包含多個類
    項目Project模塊1模塊2模塊3包1包2XxxDemo01.javaXxxDemo02.java

    IDEA中常用的快捷鍵

    • 格式化: ‘Ctrl + alt + L’
    • 注釋: ‘ctrl + /’
    • 行移動: ‘alt + shift + 上下箭頭’
    • 復制行: ‘ctrl + D’

    IDEA中模塊操作

    • 新建模塊:

      • File -> Project Structure -> New Module -> +號 -> New Module ->選則JDK -> 修改模塊名
    • 刪除模塊:

      • 選擇需要刪除的模塊 -> Remove Module
      • 以上刪除,模塊只是在IDEA中不顯示,在硬盤上還是存在的.需要到模塊對應的目錄刪除
    • 導入模塊:

      • File -> Project Structor -> +號 -> Import Module ->

    第五章 數組

    數組的定義格式

    數組: 是一種用于存儲多個相同類型數據的存儲模型

    /*格式1:數據類型[] 變量名int[] arr解讀: 定義了一個int類型的數據,數組名是arr */ /*格式2:數據類型 變量名[]int arr[]解讀: 定義了一個int類型的變量,變量名是arr數組 */

    數組初始化之動態初始化

    Java中的數組必須先初始化,然后才能使用

    所謂初始化: 就是為數組中的數組元素分配內存空間,并為每個數組元素賦值

    動態初始化

    初始化時只指定數組長度,由系統為數組分配初始值

    • 格式: 數據類型[] 變量名 = new 數組類型[數組長度]
    • 范例: int[] arr = new int[3]
    public class ArrayDemo {public static void main(String[] args) {int[] arr = new int[3];// 輸出數組名System.out.println(arr); // [I@58ceff1System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr[2]);} }

    內存分配

    Java程序在運行時,需要在內存中分配空間。為了提高運算效率,就對空間進行了不同區域的劃分,因為每一片區域都有特定的處理數據方式和內存管理方式.看下面一段代碼:

    int[] arr = new int[3]; System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]);

    【棧內存】: 存儲局部變量定義在方法中的變量,例如arr使用完畢,立即消失

    【堆內存】: 存儲new出來的內容(實體、對象)

    數組在初始化時,會為存儲空間添加默認值:

    • 整數: 默認值0
    • 浮點數: 默認值0.0
    • 布爾值: 默認值是false
    • 字符: 默認值是空字符
    • 引用數據類型: 默認值是null

    每一個new出來的東西都有一個地址值,使用完畢,會在垃圾回收器空閑時被回收

    數組內存圖(單個數組)

    public class ArrarTest01{public static void main(String[] args){// 定義一個數組int[] arr = new int[3];// 輸出數組名及元素System.out.println(arr);System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr[2]);// 給數組中的元素賦值arr[0] = 100;arr[2] = 200;// 再次輸出數組名及元素System.out.println(arr);System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr[2]);} }

    數組內存圖(多個數組)

    public class ArrayTest02{public static void main(String[] args){// 定義兩個數組int[] arr = new int[2];int[] arr2 = new int[3];// 分別輸出數組名及元素System.out.println(arr);System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr2);System.out.println(arr[0]);System.out.println(arr[2]);// 然后分別給數組中的元素賦值arr[0] = 100;arr2[0] = 200;arr2[2] = 300;// 分別再次輸出System.out.println(arr);System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr2);System.out.println(arr[0]);System.out.println(arr[2]);} }

    數組內存圖(多個數組指向相同)

    public class ArrayTest03{public static void main(String[] args){// 定義一個數組int[] arr = new int[3];arr[0] = 100;arr[1] = 200;arr[2] = 300;System.out.println(arr);System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr[2]);// 定義第二個數組指向第一個數組int[] arr2 = arr;arr2[0] = 111;arr2[1] = 222;arr2[2] = 333;// 輸出兩個數組的名及元素System.out.println(arr);System.out.println(arr[0]);System.out.println(arr2);System.out.println(arr2[0]);} }

    數組初始化之靜態初始化

    靜態初始化: 初始化時指定每個數組元素的初始值,由系統決定數組長度

    int[] arr= new int[]{1,2,3};// 簡寫 int[] arr= {1,2,3};

    數組操作的兩個常見小問題

    索引越界

    訪問了數組中不存在的索引對應的元素,造成索引越界問題

    int[] arr = new int[3]; System.out.println(arr[3]); // 數組越界

    空指針異常

    訪問的數組已經不再指向堆內存的數據,造成空指針異常

    int[] arr = new int[3]; arr = null; System.out.println(arr[0]);

    數組常見操作

    遍歷

    public class ArrayTest01{public static void main(String[] args){int[] arr = {11, 22, 33, 44, 55};for(int i = 0;i < arr.length; i++){System.out.println(arr[i]);}} }

    獲取最值

    public class ArrayTest02{public static void main(String[] args){int[] arr = {12, 45, 98, 73, 60};int max = arr[0];for(int i = 1; i< arr.length; i++){if(arr[i] > max){max = arr[i];} }System.out.println(max);} }

    第六章 方法

    什么是方法

    方法是將具有獨立功能的代碼塊組織成為一個整體,使其具有特殊功能的代碼集

    注意:

    • 方法必須先創建才可以使用,該過程成為方法定義
    • 方法創建后并不是直接運行的,需要手動使用后才執行,該過程成為方法調用.

    方法的定義和調用

    public class MethodDemo{public static void main(String[] args){isEvenNumber();}// 需求: 定義一個方法,在方法中定義一個變量,判斷該數據是否是偶數public static void isEvenNumber(){// 定義變量int number = 10;if(number %2 == 0){System.out.println("true")} else {System.out.println("false");}} }

    流程梳理:

    • 首先會加載main方法中的代碼塊
    • 當遇到isEventNumber時,會去尋找isEvenNumber方法,并進入到該方法
    • 執行完isEventNumber之后,會返回執行環境給main函數

    【栗子】: 設計一個方法,用于打印兩個數中的較大數

    public class MethodTest{public static void main(String[] args){printMax(10, 20);}public static void printMax(int x, int y){if(x > y){System.out.println(x);} else {System.out.println(y);}} }

    帶參數方法的定義和調用

    方法定義時,注意:

    • 參數中的數據類型與變量名都不能缺少,缺少任意一個程序將報錯
    • 多個參數之間使用逗號分隔.

    【栗子】: 定義一個方法,接收一個參數,判斷這個數是否為偶數

    public class MehtodTest01{public static void main(String[] args){isEvent(15);}public static void isEvent(int x){if(x % 2 == 0){System.out.println(true);} else {System.out.println(false);}} }

    方法的注意事項

    • 方法不能嵌套定義
    // 錯誤的演示 public static void methodOne(){// 代碼塊1public static void methodTwo(){// 代碼塊2} }// 正確的定義 public static void methodOne(){// 代碼塊1 } public static void methodTwo(){// 代碼塊2 }
    • void表示無返回值,可以省略return,也可以單獨的書寫return,后面不加數據
    public static void methodDemo{// 代碼片段,省略return }// 或 public static void methodDemo{// 代碼片段return; }

    方法的通用格式

    /*public static 返回值類型 方法名(參數){方法體;return 數據;} */

    方法重載

    public class MethodDemo{public static int sum(int a, int b){return a + b;}public static int sum(int a, int b, int c) {return a + b + c;} }

    方法重載: 同一個類中定義的多個方法之間的關系,滿足下列條件的多個方法相互構成重載

    • 多個方法在同一個類中
    • 多個方法具有相同的方法名
    • 多個方法的參數不同(數量或類型不同)

    【方法重載的特點】

    • 重載僅對應方法的定義,與方法的調用無關,調用方式參照標準格式
    • 重載僅針對同一個類中方法的名稱與參數進行識別,與返回值無關,換句話說不能通過返回值來判定兩個方法是否相互構成重載.
    // 以下兩個未構成重載 public class MethodDemo{public static void fn(int a) {// 方法體}public static int fn(int a) {// 方法體} }

    【栗子】: 使用方法重載的思想,設計比較兩個整數是否相同的方法,兼容全整數類型(byte, short, int, long)

    public class MethodTest01{public static void main(String[] args){System.out.println(compare(10, 20));System.out.println(compare((byte) 10, (byte) 20));System.out.println(compare((short) 10,(short) 20));System.out.println(compare(10L, 20L));}public static boolean compare(int a, int b){return a == b;}public static boolean compare(byte a, byte b){return a == b;}public static boolean compare(short a, short b){return a == b;}public static boolean compare(long a, long b){return a == b;} }

    方法的參數傳遞

    基本類型

    public class ArgsDemo01{public static void main(String[] args){int number = 100;System.out.println('調用change方法前:' + number);change(number);System.out.println('調用change方法后:' + number);}public static void change(int number){number = 200;} }

    對于基本數據類型的參數,形式參數的改變,不影響實際參數的值

    引用類型

    public class ArgsDemo02{public static void main(String[] args){int[] arr = {10, 20, 30};System.out.println('調用change方法前:' + arr[1]);change(arr);System.out.println('調用change方法后:' + arr[1]);}public static void change(int[] arr) {arr[1] = 200;} }

    對于引用類型的參數,形式參數的改變,影響實際參數的值

    【栗子1】: 設計一個方法用于數組遍歷,要求遍歷的結果是在一行上的。例如:[11, 22, 33, 44, 55]

    System.out.prinln(): 輸出內容換行

    System.out.print(): 輸出內容不換行

    public class MethodTest01 {public static void main(String[] args) {int[] arr = {11, 22, 33, 44, 55};printArray(arr);}public static void printArray(int[] arr) {System.out.print("[");for (int i = 0; i < arr.length; i++) {if (i != arr.length - 1) {System.out.print(arr[i] + ", ");} else {System.out.print(arr[i]);}}System.out.print("]");} }

    【栗子2】: 設計一個方法用于獲取數組中元素的最大值,調用方法并輸出結果

    public class MethodTest02 {public static void main(String[] args) {int[] arr = {1, 3, 5, 4, 2, 8, 9};System.out.println(getMax(arr));}public static int getMax(int[] arr) {int max = arr[0];for (int i = 1; i < arr.length; i++) {if (arr[i] > max) {max = arr[i];}}return max;} }

    【栗子3】: 輸入星期數,顯示今天的減肥活動(周一: 跑步, 周二: 游泳, 周三: 慢走, 周四: 動感單車, 周五: 拳擊, 周六: 爬山, 周日: 好好吃一頓)

    public class Test01 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入星期數: ");int day = sc.nextInt();while (day < 1 || day > 7) {System.out.println("請輸入整數 1~7");day = sc.nextInt();}if (day == 1) {System.out.println("跑步");}if (day == 2) {System.out.println("游泳");}if (day == 3) {System.out.println("慢走");}if (day == 4) {System.out.println("動感單車");}if (day == 5) {System.out.println("拳擊");}if (day == 6) {System.out.println("爬山");}if (day == 7) {System.out.println("好好吃一頓");}} }

    【栗子4】: 朋友聚會的時候可能會玩一個游戲: 逢七過。規則是: 從任意一個數字開始報數,當你要報的數字包含7或者是7的倍數時都要說: 過.為了幫助大家更好的玩這個游戲,這里我們直接在控制臺打印1~100之間的滿足逢七過規則的數據.

    public class Test02 {public static void main(String[] args) {for (int i = 1; i < 100; i++) {if (i % 7 == 0 || i / 10 % 10 == 7 || i % 10 == 7) {System.out.println(i);}}} }

    【栗子5】: 有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第3個月后每個月又生一對兔子,假如兔子都不死,問第二十個月的兔子對數為多少?

    思路:

    第1個月兔子對數為 1 對

    第2個月兔子對數為 1 對

    第3個月兔子對數為 2 對

    第4個月兔子對數為 3 對

    第5個月兔子對數為 5 對

    即 a[n] = a[n-1] + a[n-2];用動態規劃

    public class Test03 {public static void main(String[] args) {int[] arr = new int[20];arr[0] = 1;arr[1] = 1;for (int i = 2; i < 20; i++) {arr[i] = arr[i - 1] + arr[i - 2];}System.out.println(arr[19]);} }

    【栗子6】: 我國古代數學家張丘建在《算經》一書中提出的數學問題: 雞翁一值錢五,雞母一值錢三,雞雌三值錢一。問雞翁、雞母、雞雌各幾何?

    思路:

    假設 雞翁、雞母、雞雌 的數量各為 x , y, z 有以下等式成立

    x + y + z = 100

    5x + 3y + z/3 = 100

    0<= x <= 20

    0<=y <= 33

    0<= z <= 100

    循環遍歷 x和y, 讓 z = 100 - x - y; 然后z要能整除3 以及 滿足等式 5x + 3y + z/3 = 100

    public class Test04 {public static void main(String[] args) {for (int x = 0; x <= 20; x++) {for (int y = 0; y <= 33; y++) {int z = 100 - x - y;if (z % 3 == 0 && 5 * x + 3 * y + z / 3 == 100) {System.out.println(x + " " + y + " " + z);}}}} }

    第七章 類和對象

    萬物皆對象,客觀存在的事物皆稱為對象

    什么是類

    : 是對現實生活中一類具有共同屬性和行為的事物的抽象

    類的特點:

    • 類是對象的數據類型
    • 類是具有相同屬性和行為的一組對象的集合

    對象: 是能夠看得見摸得著的真實存在的實體

    對象的屬性: 對象具有各種特征,每個對象的每個屬性都有特定的值

    對象的行為: 對象能夠執行的操作

    類的定義

    類的重要性: 是Java程序的基本組成單位

    • 類的組成: 屬性和行為
      • 屬性: 在類中通過成員變量來體現(類中方法外的變量)
      • 行為: 在類中通過成員方法來體現(和前面的方法相比去掉static關鍵字即可)
    /*模板 public class 類型{// 成員變量變量1的數據類型 變量1;變量2的數據類型 變量2;...// 成員方法方法1;方法2;... }*/// 栗子如下 public class Phone {// 成員變量String brand;int price;// 成員方法public void call() {System.out.println("打電話");}public void sendMessage() {System.out.println("發短信");} }

    對象的使用

    • 創建對象:
      • 格式: 類名 對象名 = new 類名();
      • 范例: Phone p = new Phone();
    • 使用對象:
      • 使用成員變量:
        • 格式: 對象名.變量名
        • 范例:p.brand
      • 使用成員方法:
        • 格式: 對象名.方法名()
        • 范例: p.call()
    public class PhoneDemo {public static void main(String[] args) {// 創建對象Phone p = new Phone();// 使用成員變量System.out.println(p.brand);System.out.println(p.price);p.brand = "華為";p.price = 2999;System.out.println(p.brand);System.out.println(p.price);// 使用成員方法p.call();} }

    【栗子】: 首先定義一個學生類,然后定義一個學生測試類,在學生測試類中通過對象完成成員變量和成員方法的使用

    // Student.java public class Student{// 成員變量String name;int age;// 成員方法public void study(){Syste.out.println("好好學習,天天向上");}public void doHomework(){System.out.println("代碼敲爛,月薪過萬");} } // StudentDemo.java public class StudentDemo{public static void main(String[] args){Student s = new Student();System.out.println(s.name + "," + s.age);s.name="林青霞";s.age = 30;System.out.println(s.name + "," + s.age);s.study();s.doHomework();} }

    多個對象指向相同

    public class StudentTest03{public static void main(String[] args){Student s1 = new Student();s1.name = "林青霞";s1.age = 30;System.out.println(s1.name + "," + s1.age);Student s2 = s1;s2.name = "張曼玉";s2.age = 28;System.out.println(s1.name + "," + s1.age);System.out.println(s2.name + "," + s2.age);} }

    成員變量和局部變量

    public class Student {String name;public void study(){int i = 0;System.out.println("好好學習");}public void doHomework(){System.out.println("多做練習");int j = 0;}int age; }

    成員變量: 類中方法外的變量

    局部變量: 方法中的變量

    區別成員變量局部變量
    類中位置不同類中方法外方法內或者方法聲明上
    內存中位置不同堆內存棧內存
    生命周期不同隨著對象的存在而存在,隨著對象的消失而消失隨著方法的調用而存在,隨著方法的調用完畢而消失
    初始值不同有默認的初始化值沒有默認的初始化值,必須先定義,賦值,才能使用

    封裝

    private

    • 是一個權限修飾符
    • 可以修飾成員(成員變量和成員方法)
    • 作用是保護成員不被別的類使用,被private修飾的成員只能在本類中才能訪問

    針對private修飾的成員變量,如果需要被其他類使用,提供相應的操作

    • 提供"get變量名()"方法,用于獲取成員變量的值,方法用public修飾
    • 提供"set變量名(參數)"方法,用于設置成員變量的值,方法用public修飾

    【栗子】:

    // Student.java public class Student{String name;int age;public void show(){System.out.println(name + "," + age);} }// 使用private關鍵字 public class Student {String name;private int age;// 提供get/set方法public void setAge(int a){if(a < 0 || a > 180){System.out.println("您給的年齡有誤");} else {age = a;}}public int getAge(){return age;}public void show(){System.out.println(name + "," + age);} }

    this

    public class Student {private String name;public void setName(String name){this.name = name;}public void show(){System.out.println(this.name);} }public class StudentDemo{public static void main(String[] args){Student s = new Student();s.setNmae("Marron");s.show();} }
    • this修飾的變量用于指代成員變量

      • 方法的形參與成員變量同名,不帶this修飾的變量指的是形參,而不是成員變量

      • public class Student{private String name;public String getName(){return name;}public void setName(String name){// 此處name指向形參,this.name執行成員變量this.name = name;} }
      • 方法的形參沒有與成員變量同名,不帶this修飾的變量指的是成員變量

    小結

  • 封裝概述
  • 面向對象三大特征之一(封裝、繼承、多態)

    是面向對象編程語言堆客觀世界的模擬,客觀世界成員變量都是隱藏在對象內部的,外界無法直接操作的

  • 封裝原則
  • 將類的某些信息隱藏在類內部,不允許外部程序直接訪問,而是通過該類提供的方法來實現堆隱藏信息的操作和訪問成員變量private,提供對應的getXxx()/setXxx()方法

    public class Student{private String name;public String getName(){return name;}public void setNamee(String name) {this.name = name;} }
  • 封裝的好處
  • 通過方法來控制成員變量的操作,提高了代碼的安全性

    把代碼用方法進行封裝,提高了代碼的復用性

    構造方法

    構造方法是一種特殊的方法,其作用是用來創建對象

    /*格式:public class 類名{修飾符 類名(參數) {...}} */

    功能: 主要是完成對象數據的初始化

    public class Student {private String name;private int age;// 構造方法public Student(){System.out.println("無參構造方法");}public void show() {System.out.println(name + "," + age);} }
    • 下面使用重載和封裝的思想定義一個Student類
    public class Student {private String name;private int age;public Student() {}public Student(String name) {this.name = name;}public Student(int age) {this.age = age;}public Student(String name, int age) {this.name = name;this.age = age;}public void show() {System.out.println(name + "," + age);} }

    標準類制作

    • 成員變量: 使用private修飾
    • 構造方法: 提供一個無參構造方法,提供一個帶多個參數的構造方法
    • 成員方法:
      • 提供每一個成員變量對應的setXxx()/getXxx()
      • 提供一個顯示對象信息的show()
    • 創建對象并為其成員變量賦值的兩種方式
      • 無參構造方法創建后使用setXxx()賦值
      • 使用帶參數構造方法直接創建帶有屬性值得對象

    第八章 字符串

    API

    API(application programing interface): 應用程序編程接口

    編寫一個機器人程序去控制機器人踢足球,程序需要向機器人發出向前跑、向后跑、射門、搶球等各種命令。機器人廠商提供一些用于控制機器人的接口類,這些類中定義好了操作機器人的各種動作的方法。其實,這些接口類就是機器人廠商提供給應用程序編程的接口,大家把這些類稱為API

    Java API: 指的就是JDK中提供的各種功能的Java類

    String

    String類代表字符串,Java程序中的所有字符串文字(例如"abc")都被視為此類的實例。也就是說,Java程序中所有的雙引號字符串,都是String類的對象

    字符串的特點:

    • 字符串不可變,它們的值在創建后不能被更改

    • 雖然String的值是不可改變的,但是它們可以被共享

    • 字符串效果上相當于字符數組(char[]),但是底層原理是字節數組(byte[])

    String構造方法(常用)

    方法名說明
    public String()創建一個空白字符串對象,不含有任何內容
    public String(char[] chs)根據字符數組的內容,來創建字符串對象
    public String(byte[] bys)根據字節數組的內容,來創建字符串對象
    String s = “abc”;直接賦值的方式創建字符串對象,內容就是abc
    public class StringDemo01 {public static void main(String[] args) {String s1 = new String();System.out.println("s1: " + s1);char[] chs = {'a', 'b', 'c'};String s2 = new String(chs);System.out.println("s2: " + s2);byte[] bys = {97, 98, 99};String s3 = new String(bys);System.out.println("s3: " + s3);String s4 = "abc";System.out.println("s4: " + s4);} }

    String對象的特點

    • 通過new創建字符串對象,每一次new都會申請一個內存空間,雖然內容相同,但是地址值不同
    char[] chs = {'a', 'b', 'c'}; String s1 = new String(chs); String s2 = new String(chs); System.out.println(s1 == s2);
    • 以 ”“方式給出的字符串,只要字符序列相同(順序和大小),無論在程序代碼中出現幾次,JVM只會建立一個String對象,并在字符串池中維護
    String s3 = "abc"; String s4 = "abc"; System.out.println(s3 == s4); /*在以上代碼中,針對第一行代碼,JVM會建立一個String對象放在字符串池中,并給s3參考;第二行則讓s4直接參考字符串池中的String對象,也就是說它們本質上是同一個對象 */

    字符串的比較

    使用==做比較

    • 基本類型: 比較的是數據值是否相同
    • 引用類型: 比較的是地址值是否相同

    字符串是對象,它比較內容是否相同,是通過一個方法來實現的,這個方法叫: equals()

    • public boolean equals(Object anObject): 將此字符串與指定對象進行比較。由于我們比較的是字符串對象,所以參數直接傳遞一個字符串
    public class StringDemo02{public static void main(String[] args){// 構造方法的方式得到對象char[] chs = {'a', 'b', 'c'};String s1 = new String(chs);String s2 = new String(chs);// 直接賦值的方式得到對象String s3 = "abc";String s4 = "abc";// 比較字符串是否相同System.out.println(s1.equals(s2));System.out.println(s1.equals(s3));System.out.println(s1.equals(s4));} }

    幾個小栗子

    【栗子1】: 簡單登錄比較

    已知用戶名和密碼,請用程序實現模擬用戶登錄。總共給三次機會,登錄之后會,給出相應的提示

    public class StringTest01 {public static void main(String[] args) {// 已知用戶名和密碼,定義兩個字符串即可String username = "marron";String password = "lzhhc";for (int i = 3; i > 0; i--) {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 {if (i - 1 == 0) {System.out.println("登錄失敗");} else {System.out.printf("登錄失敗,你還有" + (i - 1) + "次機會");}}}} }

    【栗子2】: 遍歷字符串

    public class StringTest02 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入字符串: ");String line = sc.nextLine();for (int i = 0; i < line.length(); i++) {System.out.println(line.charAt(i));}} }

    【栗子3】: 統計字符次數

    需求: 鍵盤錄入一個字符串,統計該字符串中大寫字母字符,小寫字母字符,數字字符出現的次數(不考慮其他字符)

    public class StringTest03 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入字符串");String print = sc.nextLine();int upper = 0;int lower = 0;int number = 0;for (int i = 0; i < print.length(); i++) {char ch = print.charAt(i);if ('0' <= ch && ch <= '9') {number++;}if ('a' <= ch && ch <= 'z') {lower++;}if ('A' <= ch && ch <= 'Z') {upper++;}}System.out.println("大寫字母個數為: " + upper);System.out.println("小寫字母個數為: " + lower);System.out.println("數字個數為: " + number);} }

    【栗子4】: 拼接字符串

    需求: 定義一個方法,把int數組中的數據按照指定的格式拼接成一個字符串返回,調用該方法,并在控制臺輸出結果。

    例如: 數組為 int[] arr = {1, 2, 3}, 執行方法后的輸出結果為: [1, 2, 3];

    public class StringTest04 {public static void main(String[] args) {int[] arr = {1, 2, 3};System.out.println(arr2String(arr));}public static String arr2String(int[] arr) {String str = "";str += "[";for (int i = 0; i < arr.length; i++) {if (i != arr.length - 1) {str += arr[i] + ", ";} else {str += arr[i];}}str += "]";return str;} }

    【栗子5】: 字符串反轉

    需求: 定義一個方法,實現字符串反轉。鍵盤錄入一個字符串,調用該方法后,再控制臺輸出結果.

    例如,鍵盤錄入abc,輸出結果cba

    public class StringTest05 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入一個字符串");String str = sc.nextLine();System.out.printf(reverseStr(str));}public static String reverseStr(String s) {String tmpS = "";for (int i = s.length() - 1; i >= 0; i--) {tmpS += s.charAt(i);}return tmpS;} }

    String常用方法

    方法說明
    public boolean equals(Object anObject)比較字符串的內容,嚴格區分大小寫(用戶名和密碼)
    public char charAt(int index)返回指定索引處的char值
    public int length()返回此字符串的長度

    StringBuilder

    Public static void main(String[] args){String s = "hello";s += "world";System.out.println(s); }

    首先在棧內存中加載方法: main

    然后執行 String s = "hello".

    • 會在堆內存的常量池創建一個"hello",編號為001
    • 將001賦值給s

    然后執行 s += "world"

    • 會在堆內存的常量池創建一個"world",編號為002
    • 在堆內存的常量池創建一個"helloworld",編號003
    • 將003賦值給s

    最后執行"System.out.println(s)"

    • 輸出s時,會根據003找到"helloworld",然后輸出

    如果堆字符串進行拼接操作,每次拼接,都會構建一個新的String對象,既耗時,又浪費內存空間,而這種操作還不可避免。可以使用Java提供的 StringBuilder類來解決這個問題。

    StringBuilder是一個可變的字符串類,我們可以把它看成是一個容器,這里的可變指的是StringBuilder對象中的內容是可變的

    方法名說明
    public String Builder()創建一個空白可變字符串對象,不含又任何內容
    public StringBuilder(String str)根據字符串的內容,來創建可變字符串對象
    public class StringBuilderDemo01{public static void main(String[] args){StringBuilder sb = new StringBuilder();System.out.println("sb: " + sb); // System.out.println("sb.length(): " + sb.length()); // 0StringBuilder sb2 = new StringBuilder("hello");System.out.println("sb2: " + sb2); // "hello"System.out.println("sb2.length(): " + sb2.length()); // 5} } 方法名說明
    public StringBuilder append(任意類型)添加數據,并返回對象本身
    public StringBuilder reverse()返回相反的字符序列
    public class StringBuilderDemo01{public static void main(String[] args){// 創建對象StringBuilder sb = new StringBuilder();StringBuilder sb2 = sb.append("hello");System.out.println("sb: " + sb); // "hello"System.out.println("sb2: " + sb2); // "hello"System.out.prtinln(sb == sb2); // truesb.append("hello");sb.append("world");sb.append("java");sb.append(100);/* 鏈式編程sb.append("hello").append("world").append("java").append(100);*/System.out.println("sb: " + sb); // helloworldjava100sb.reverse();System.out.println("sb: " + sb); // 001avajdlrowolleh} }

    StringBuilder和String相互轉換

    StringBuilder轉換為String:

    • public String toString(): 通過toString()就可以實現把StringBuilder轉換為String

    String轉換為StringBuilder

    • public StringBuilder(String s): 通過構造方法就可以實現把String轉換為StringBuilder
    public class StringBuilderDemo02{public static void main(String[] args){StringBuilder sb = new StringBuilder();sb.append("hello");// StringBuilder轉換為StringString s = sb.toString();System.out.println(s);// String轉換為StringBuilderString s = "hello";StringBuilder sb = new StringBuilder(s);System.out.println(sb);} }

    StringBuildr小栗子

    【栗子1】: 拼接字符串

    需求: 定義一個方法,把int數組中的數據按照指定的格式拼接成一個字符串返回,調用該方法,并在控制臺輸出結果.

    例如: 數組為int[] arr = {1, 2, 3}; 執行方法后的輸出結果為: [1, 2, 3]

    public class StringBuilderTest01 {public static void main(String[] args) {int[] arr = {1, 2, 3};System.out.printf(arr2String(arr));}public static String arr2String(int[] arr) {StringBuilder sb = new StringBuilder();sb.append("[");for (int i = 0; i < arr.length; i++) {if (i != arr.length - 1) {sb.append(arr[i]);sb.append(", ");} else {sb.append(arr[i]);}}sb.append("]");String str = sb.toString();return str;} }

    【栗子2】: 字符串反轉

    需求: 定義一個方法,實現字符串反轉。鍵盤錄入一個字符串,調用該方法后,在控制臺輸出結果

    例如: 鍵盤錄入abc,輸出結果cba

    public class StringBuilderTest02 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入字符串: ");String str = sc.nextLine();System.out.println(reverseStr(str));}public static String reverseStr(String s){StringBuilder sb = new StringBuilder(s);return sb.reverse().toString();} }

    第九章 集合之ArrayList

    編程的時候如果要存儲多個數據,使用長度固定的數組存儲格式,不一定能滿足我們的需求,更適應不了變化的需求,那么,此時該如何選擇呢?

    集合概述: 集合類的特點是,提供了一種存儲空間可變的存儲模型,存儲的數據容量可以發生改變.下面主要學習ArrayList

    ArrayList:

    • 可調整大小的數組實現
    • : 是一種特殊的數據類型,泛型。

    ArrayList構造方法和添加方法

    方法名說明
    public ArrayList()創建一個空的集合對象
    public boolean add(E e)將指定的元素追加到此集合的末尾
    public void add(int index, E element)此集合中的指定位置插入指定的元素
    import java.util.ArrayList;public class ArrayListDemo01 {public static void main(String[] args) {// 創建一個空集合對象ArrayList<String> array = new ArrayList<>();// 輸出集合System.out.println("array: " + array);// 添加元素array.add("hello");array.add("world");array.add("java");System.out.println("array: " + array);// 在指定位置添加元素array.add(1, "javaSE");System.out.println("array: " + array);} }

    ArrayList集合常用方法

    方法名說明
    public boolean remove(Object o)刪除指定的元素,返回刪除是否成功
    public E remove(int index)刪除指定索引處的元素,返回被刪除的元素
    public E set(int index, E element)修改指定索引處的元素,返回被修改的元素
    public E get(int index)返回指定索引處的元素
    public int size()返回集合中的元素的個數
    import java.util.ArrayList;public class ArrayListDemo02 {public static void main(String[] args) {ArrayList<String> array = new ArrayList<>();array.add("hello");array.add("world");array.add("java");// 輸出集合 // System.out.println("array: " + array);// 刪除 // array.remove("world"); // System.out.println("array: " + array);// 刪除: 按索引 // array.remove(0); // System.out.println("array: " + array);// 修改:指定索引處 // array.set(2, "javaSE"); // System.out.println("array: " + array);// 查詢: 索引處的元素 // System.out.println(array.get(2)); // System.out.println("array: " + array);// 集合長度System.out.println(array.size());} }

    【小栗子】: 遍歷集合

    需求: 創建一個存儲字符串的集合,存儲3個字符串元素,使用程序實現在控制臺遍歷該集合

    import java.util.ArrayList;public class ArrayListTest02 {public static void main(String[] args) {// 創建集合對象ArrayList<String> array = new ArrayList<>();// 在集合中添加字符串對象array.add("Marron");array.add("Mar");array.add("lzhhc");// 遍歷集合for (int i = 0; i < array.size(); i++) {System.out.println(array.get(i));}} }

    【小栗子】: 存儲學生對象并遍歷

    需求: 創建一個存儲學生對象的集合,存儲3個學生對象,使用程序實現在控制臺遍歷該集合

    • 學生類如下:
    // Student.java public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public void setName(String name) {this.name = name;}public String getName() {return name;}public void setAge(int age) {this.age = age;}public int getAge() {return age;} } import java.util.ArrayList;public class ArrayListTest02 {public static void main(String[] args) {// 創建集合對象ArrayList<Student> StudentList = new ArrayList<>();// 創建學生對象Student s1 = new Student("Marron", 18);Student s2 = new Student("Mar", 17);Student s3 = new Student("lzhhc", 19);// 添加元素到集合中StudentList.add(s1);StudentList.add(s2);StudentList.add(s3);for (int i = 0; i < StudentList.size(); i++) {Student tmpStu = StudentList.get(i);System.out.println(tmpStu.getName() + "今年" + tmpStu.getAge() + "歲");}} }

    【小栗子】: 存儲學生對象并遍歷(帶輸入)

    需求: 創建一個存儲學生對象的集合,存儲3個學生對象,使用程序在控制臺實現遍歷該集合學生的姓名和年齡來自鍵盤錄入

    import java.util.ArrayList; import java.util.Scanner;public class ArrayListTest03 {public static void main(String[] args) {ArrayList<Student> array = new ArrayList();addStudent(array);addStudent(array);addStudent(array);for (int i = 0; i < array.size(); i++) {Student s = array.get(i);System.out.println(s.getName() + "," + s.getAge());}}public static void addStudent(ArrayList<Student> array) {Scanner sc = new Scanner(System.in);System.out.println("請輸入學生姓名");String name = sc.nextLine();System.out.println("請輸入學生年齡");int age = sc.nextInt();Student s = new Student();s.setName(name);s.setAge(age);array.add(s);} }

    總結

    以上是生活随笔為你收集整理的Java --- 基础学习Ⅰ的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。