Java學習連載002

第五天:數組、方法和字符串

  1. 數組

    • 定義數組的語法:
    T[] x = new T[size];
    T[] y = { value1, value2, ... };
    • 操作數組元素可以使用下標運算[ ],數組的下標範圍0-(數組大小-1)。
    • 數組有一個length屬性表示數組元素的個數。
    • 通常可以用循環來對數組中的元素進行操作。
  2. 二維數組

    • 定義二維數組的語法:
    T[][] x = new T[size1][size2];
    T[][] y = new T[size][];
    T[][] z = {{v1, v2}, {v3, v4, v5, v6}, {v7}};
    • 二維數組的應用場景:表格、矩陣、棋盤、2D遊戲中的地圖。
  3. 方法的定義和使用

    public static T foo(T1 param1, T2 param2, ...) {
        // 方法體
    }
  4. 方法的遞歸調用

    • 方法直接或間接的調用自身
  5. 字符串用法及常用方法

    • 字符串對象的創建
        String s1 = "Hello";
        String s1 = new String("Hello");
    • 字符串常用方法
      • es:比較兩個字符串內容是否相同qual
      • equalsIgnoreCase:忽略大小寫比較兩個字符串內容是否相同
      • compareTo:比較兩個字符串的大小
      • length:計算字符串的長度
      • concat:字符串連接
      • charAt:從字符串中取指定位置的字符
      • indexOf/lastIndexOf:字符串的匹配
      • trim:修剪字符串左右兩端的空白
      • toUpperCase/toLowerCase:將字符串變成大寫/小寫
      • substring:從字符串中取指定位置的子串
      • startsWith/endsWith:判斷字符串是否以指定的字符串開頭/結尾
      • replace:將字符串中指定內容替換爲另外的字符串

練習1:錄入5名學生的成績,計算平均分,找出最高分和最低分。

package com.lovoinfo;

import java.util.Scanner;

public class Test01 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String[] names = {"關羽", "張飛", "趙雲", "黃忠", "馬超"};
        double[] scores = new double[5];
        double sum = 0;
        for(int i = 0; i < scores.length; i++) {
            System.out.print("請輸入" + names[i] + "的成績: ");
            scores[i] = sc.nextDouble();
            sum = sum + scores[i];
        }

        System.out.println("平均分爲: " + sum / scores.length);

        int maxIndex = 0, minIndex = 0;
        for(int i = 1; i < scores.length; i++) {
            if(scores[i] > scores[maxIndex]) {
                maxIndex = i;
            }
            else if(scores[i] < scores[minIndex]) {
                minIndex = i;
            }
        }

        System.out.println(names[maxIndex] + "考了最高分" + scores[maxIndex]);
        System.out.println(names[minIndex] + "考了最低分" + scores[minIndex]);

        sc.close();
    }
}

練習2:輸出前20個Fibonacci數。
1, 1, 2, 3, 5, 8, 13, 21, 34, …

package com.lovoinfo;

/**
 * 輸出前20個Fibonacci數
 * @author jackfrued
 *
 */
public class Test04 {

    public static void main(String[] args) {
        int[] f = new int[20];
        f[0] = f[1] = 1;

        for(int i = 2; i < f.length; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }

        for(int x : f) {
            System.out.println(x);
        }
    }
}

練習3:隨機產生10個數,並對其進行排序。

package com.lovoinfo;

public class Test05 {

    public static void main(String[] args) {
        int[] a = new int[10];

        System.out.println("排序前: ");
        for (int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 100);
            System.out.print(a[i] + "\t");
        }

        bubbleSort(a);

        System.out.println("\n排序後: ");
        for (int x : a) {
            System.out.print(x + "\t");
        }
    }

    /**
     * 冒泡排序
     * @param a 待排序的數組
     */
    public static void bubbleSort(int[] a) {
        // N個元素排序需要N-1趟循環
        for (int i = 0; i < a.length - 1; i++) {
            // 相鄰元素兩兩比較
            for(int j = 0; j < a.length - 1 - i; j++) {
                if(a[j] > a[j + 1]) {   // 如果前面元素大於後面元素就交換
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }

    /**
     * 簡單選擇排序
     * @param a 待排序的數組
     */
    public static void selectionSort(int[] a) {

        for (int i = 0; i < a.length - 1; i++) {
            int minIndex = i; // 假設當前的i是最小元素所在的位置
            for (int j = i + 1; j < a.length; j++) {
                if (a[j] < a[minIndex]) { // 發現更小的元素
                    minIndex = j; // 記錄更小的元素所在的位置
                }
            }
            // 將i位置上的元素和最小元素交換位置
            int temp = a[i];
            a[i] = a[minIndex];
            a[minIndex] = temp;
        }
    }
}

練習4:輸入5個學生三門課的成績,計算每個學生的平均分以及每門課程的平均分。

package com.lovoinfo;

import java.util.Scanner;

public class Test07 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String[] stuNames = {"關羽", "張飛", "趙雲", "黃忠", "馬超"};
        String[] subNames = {"語文", "數學", "英語"};
        int[][] scores = new int[stuNames.length][subNames.length];

        for(int i = 0; i < scores.length; i++) {
            System.out.println("請錄入" + stuNames[i] + "的成績");
            for(int j = 0; j < scores[i].length; j++) {
                System.out.print("\t" + subNames[j] + ": ");
                scores[i][j] = sc.nextInt();
            }
        }

        // 後面的代碼自行完成

        sc.close();
    }
}

練習5:輸出10行楊輝三角。

package com.lovoinfo;


/**
 * 楊輝三角
 * @author jackfrued
 *
 */
public class Test08 {

    public static void main(String[] args) {
        int[][] y = new int[10][];
        for(int i = 0; i < y.length; i++) {
            y[i] = new int[i + 1];
            for(int j = 0; j < y[i].length; j++) {
                if(j == 0 || j == i) {
                    y[i][j] = 1;
                }
                else {
                    y[i][j] = y[i - 1][j] + y[i - 1][j - 1];
                }
            }
        }

        for(int[] a : y) {
            for(int b : a) {
                System.out.print(b + "\t");
            }
            System.out.println();
        }
    }
}

練習6:輸入用戶名和密碼,驗證用戶身份。

package com.lovoinfo;

import java.util.Scanner;

/**
 * 用戶登錄驗證
 * @author jackfrued
 *
 */
public class Test03 {

    /**
     * 在數組中查找有沒有指定的元素
     * @param x 數組
     * @param y 指定的元素
     * @return 找到了返回元素在數組中的位置,沒有找到返回-1
     */
    public static int findUsername(String[] x, String y) {
        for(int i = 0; i < x.length; i++) {
            if(x[i].equals(y)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String[] usernames = {"admin", "jack", "guest"};
        String[] passwords = {"123456", "abcdefg", "000000"};
        Scanner sc = new Scanner(System.in);
        boolean isLogin = false;    // 是否登錄成功
        do {
            System.out.print("請輸入用戶名: ");
            String username = sc.nextLine().trim();
            System.out.print("請輸入密碼: ");
            String password = sc.nextLine();
            int index = findUsername(usernames, username);
            if(index != -1) {
                if(password.equals(passwords[index])) {
                    isLogin = true;
                }
            }
            if(!isLogin) {
                System.out.println("用戶名或密碼錯誤!!!");
            }
        } while (!isLogin);
        // 登錄成功就結束do...while循環顯示歡迎信息
        System.out.println("登錄成功!歡迎使用本系統...");
        sc.close();
    }
}

練習7:跑馬燈效果。

package com.lovoinfo;

public class Test04 {

    public static void main(String[] args) throws InterruptedException {
        String str = "歡迎來朗沃學習        ";

        while(true) {
            System.out.println(str);
            str = str.substring(1) + str.charAt(0);
            Thread.sleep(200);
        }

    }
}

練習8:實現字符串倒轉、字符串去掉空格、字符串大小寫互換的方法。

package com.lovoinfo;

public class Test05 {

    /**
     * 字符串倒轉
     * @param str 原來的字符串
     * @return 倒轉後的字符串
     */
    public static String reverse(String str) {
        String newStr = "";
        for(int i = str.length() - 1; i >= 0; --i) {
            newStr += str.charAt(i);
        }
        return newStr;
    }

    /**
     * 修剪字符串中所有的空白字符
     * @param str 原來的字符串
     * @return 去掉空白字符後的字符串
     */
    public static String trimAll(String str) {
        String newStr = "";
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) != ' ') {
                newStr += str.charAt(i);
            }
        }
        return newStr;
    }

    /**
     * 將字符串中的小寫字母變大寫,大寫字母變小寫
     * @param str 原來的字符串
     * @return 變換後的字符串
     */
    public static String switchUpperLower(String str) {
        String newStr = "";
        for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if(ch >= 'A' && ch <= 'Z') {
                ch += 32;   // 相當於 ch = (char)(ch + 32);
            }
            else if(ch >= 'a' && ch <= 'z') {
                ch -= 32;   // 相當於 ch = (char)(ch - 32);
            }
            newStr += ch;
        }
        return newStr;
    }

    public static void main(String[] args) {
        // hELLO, wORLD!
        System.out.println(switchUpperLower("Hello, World!"));

        System.out.println(reverse("hello"));   // olleh
        System.out.println(reverse("我愛你")); // 你愛我
        System.out.println(reverse("i love you"));  // uoy evol i

        System.out.println(trimAll(" h   e l l    o     "));    // hello
    }
}

Java基礎思維導圖

這裏寫圖片描述

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