第三週學習日曆

XYu1230發表於2024-07-20

這一週在練車,感覺練學車好難...
在空餘時間我也學習了Java的一些知識,在學習中自己敲了一些程式碼記錄下來...
這周最大的進步是自己根據要求寫了一個學生管理系統,雖然之前用C++寫過類似的,但是用一門新的語言,有不同的成就感>_<
7月15日參加了睿康的程式設計賽 寫出來3題半 1000多名 不知道能不能拿獎 感覺自己花200塊白坐了倆小時
演算法與資料結構這周沒學習,感覺自己第一週定的計劃也泡湯了 哈哈 沒事
鍵盤錄入

1.
//nextInt() 接收整數
//nextDouble() 接收小數
//next() 接收字串--遇到空格,製表符,回車就停止接收
2.
//nextLine();接受字串--遇到回車才會停止 
//
package Car;

public class Car {
    private String brand;
    private int price;
    private String color;

    //預設構造
    public Car() {
    }

    //有參構造
    public Car(String brand, int price, String color) {
        this.brand = brand;
        this.price = price;
        this.color = color;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void showCarInfo(){
        System.out.println(this.brand + ' ' + this.color + ' ' + this.price);
    }
}

package Car;

import java.util.Scanner;

public class CarTest {
    public static void main(String[] args){
        Car[] arr = new Car[3];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < arr.length; i++) {
            Car c = new Car();
            System.out.println("請輸入車的品牌");
            String brand = sc.next();
            c.setBrand(brand);
            System.out.println("請輸入車的顏色");
            String color = sc.next();
            c.setColor(color);
            System.out.println("請輸入車的價格");
            int price = sc.nextInt();
            c.setPrice(price);
            arr[i] = c;
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i].showCarInfo();
        }
    }
}

package Stu;

public class Student {
    private int id;
    private String name;
    private int age;


    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }

}

package Stu;

public class StudentTest {
    public static void main(String[] args) {
        Student[] arr = new Student[3];

        Student stu1 = new Student(1001,"張三",20);
        Student stu2 = new Student(1002,"李四",19);

        arr[0] = stu1;
        arr[1] = stu2;
        Student stu3 = new Student(1003,"王五",21);
        boolean flag = contains(arr,stu3);
        if(flag){
            System.out.println("學生編號重複!");
        }
        else{
            int count = countArr(arr);
            if(count < arr.length){
                arr[count] = stu3;
            }
            else {
                Student[] newArr = creatNewArr(arr);
                newArr[count] = stu3;
                arr = newArr;
            }
        }
        printArr(arr);

    }

    public static int countArr(Student[] arr){
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != null)count++;
            else break;
        }
        return count;
    }

    public static boolean contains(Student[] arr,Student stu){
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != null){
                if(arr[i].getId() == stu.getId()) return true;
            }
        }
        return false;
    }

    public static void printArr(Student[] arr){
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != null){
                System.out.println(arr[i].getId() + "  " + arr[i].getName() + "  "+ arr[i].getAge());
            }
        }
    }

    public static Student[] creatNewArr(Student[] arr){
        Student[] newArr = new Student[arr.length+1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

}


API(Application programming Interface):應用程式程式設計介面
簡單理解就是別人以及寫好的東西,直接用
Java API:指的就是JDK中提供的各種功能的Java類
字串不可變,他們的值在建立後不能被更改

package StringTest;

//String 的建構函式
public class Str {
    public static void main(String[] args) {

        //1.直接賦值
        String s1 = "abc";
        System.out.println(s1);
        //2.new關鍵字
        String s2 = new String("abcd");
        System.out.println(s2);
        //3.根據字元陣列,建立字串物件
        char[] chs = {'a','b','c','d','e'};
        String s3 = new String(chs);
        System.out.println(s3);
        //4.根據位元組陣列,建立字串物件
        byte[] bytes = {97,98,99,100,101,102};
        String s4 = new String(bytes);
        System.out.println(s4);

    }
}

字串當使用樹幹引號直接賦值時,系統會檢查該字串在串池中是否存在
不存在:建立新的
存在:複用
String直接賦值會比較節省空間,

基本資料型別比較的是資料值,引用資料型別比較的是地址值

字串比較

  • boolean equals方法(要比較的字串) 完全一樣為true,否則為false
  • boolean equalsIgnoreCase(要比較的字串) 忽略大小寫
package StringTest;

public class Equal {
    public static void main(String[] args) {

        String s1 = "abc";
        String s2 = new String("abc");
        System.out.println(s1 == s2);

        System.out.println(s1.equals(s2));

        System.out.println(s1.equalsIgnoreCase(s2));
    }

}
**鍵盤錄入的字串是new出來的**
**遍歷字串**
* public char charAt(int index); 根據索引返回字元
* public int length(); 返回字串的長度
* 字串的長度 : 字串物件.length() 
package StringTest;

import java.util.Scanner;

public class StringDemo {
    public static void main(String[] args) {
        Scanner sc =new Scanner(System.in);
        String s1 = sc.next();
        for (int i = 0; i < s1.length(); i++) {
            //字串物件.charAt(index) 取出字元
            System.out.println( s1.charAt(i) );
        }
    }
}
//字串拼接
package StringTest;

public class StringDemo2 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        String res = arrToString(arr);
        System.out.println(res);
    }

    public static String arrToString(int[] arr){
        String result = "[";
        for (int i = 0; i < arr.length; i++) {
            if(i == arr.length - 1){
                result += arr[i] + "]";
            }
            else result += arr[i] + ", ";
        }
        return result;
    }

}

package StringTest;

import java.util.Scanner;

//字串反轉
public class StringDemo3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        String result = "";
        for(int i = s.length() - 1; i >= 0; i--){
            result += s.charAt(i);
        }
        System.out.println(result);
    }
}


package me.JavaStudy;

import java.util.Scanner;
//幣值轉換
public class Captial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個數字");
        int number = sc.nextInt();
        String result = "";
        String[] arr = {"佰","什","萬","仟","佰","什","元"};
        while(number != 0){
            result = captialNumber(number%10) + result;
            number /= 10;
        }
        int count = result.length();
        for(int i = count; i < 7; i++){
            result = "零" + result;
        }
        String ans = "";
        for (int i = 0; i < result.length(); i++) {
            ans += result.charAt(i) + arr[i];
        }
        System.out.println(ans);
    }

    public static String captialNumber(int num){
        String[] arr = {"零","壹","貳","叄","肆","伍","陸","柒","捌","玖"};
        return arr[num];
    }

}

package me.JavaStudy;

public class StringDemo1 {
    public static void main(String[] args) {
        String s = "16834331202";
        String start = s.substring(0,3);
        String end = s.substring(7);
        String result = start + "****" + end;
        System.out.println(result);
    }
}

package me.JavaStudy;

//replace函式
public class StringDemo2 {
    public static void main(String[] args) {
        String s = "你好,我是張三";
        System.out.println(s);
        s = s.replace("張三","李四");
        System.out.println(s);
    }
}

StringBulider概述

StringBuilder 可以看成一個容器,建立之後裡面的內容是可變的

  • 作用: 提高字串的操作效率

使用StringBuilder的兩個場景:1.字串拼接 2.字串反轉
StringBuilder的使用案例

package me.JavaStudy;

public class StringBuliderDemo1 {
    public static void main(String[] args) {
        //1.建立物件  因為StringBuilder是Java已經寫好的類,列印物件是屬性值,而不是地址值
        StringBuilder sb = new StringBuilder("abcd");

        //2.新增元素
        sb.append(8.8888);

        int len = sb.length();
        System.out.println(len);


        //反轉操作
        sb.reverse();
        System.out.println(sb);

        //新增字串
        sb.append("abcdefg");

        //再把StringBuilder變回字串
        String s = sb.toString();
        System.out.println(s);
    }
}

迴文字串

package me.JavaStudy;

import java.util.Scanner;

public class StringBuliderDemo1 {
    public static void main(String[] args) {

        //鏈式程式設計
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個字串");
        String s =  sc.next();
        String result = new StringBuilder().append(s).reverse().toString();
        if(s.equals(result)){
            System.out.println("YES");
        }
        else System.out.println("NO");
    }
}

陣列變成字串

package me.JavaStudy;

public class StringBuliderDemo1 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        System.out.println(arrToString(arr));
    }

    public static String arrToString(int[] arr){
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < arr.length; i++) {
            if(i == arr.length - 1)sb.append(arr[i]).append("]");
            else sb.append(arr[i]).append(", ");
        }
        return sb.toString();
    }
}

StringJoiner概述

  • StringJoiner跟StringBuilder一樣,也可以看成一個容器,建立之後裡面的內容可以改變
  • 作用: 提高字串的操作效率,而且程式碼編寫特別簡潔,但是市面上很少有人用(JDK8出現的)


StringJoiner沒有空參構造

package me.JavaStudy;

import java.util.StringJoiner;

public class StringJoinerStudy {
    public static void main(String[] args) {
        StringJoiner sj = new StringJoiner("---");
        sj.add("aaa").add("bbb").add("ccc");
        System.out.println(sj);

        StringJoiner sj2 = new StringJoiner(",","[","]");
        sj2.add("1").add("2").add("3");
        String s = sj2.toString();
        System.out.println(s);
    }
}

調整字串內容

package me.JavaStudy;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        int len = a.length();
        boolean flag = check(a,b);
        if(flag) System.out.println("YES");
        else System.out.println("NO");
    }
    
    public static boolean check(String a,String b){
        for (int i = 0; i < a.length(); i++) {
            a = rotate(a);
            if(a.equals(b))return true;
        }
        return false;
    }
    
    
    public static String rotate(String s){
        return  s.substring(1) + s.charAt(0);
    }
}


字串相乘(非高精度)

package me.JavaStudy;

//字串相乘(非高精度)
public class Test2 {
    public static void main(String[] args) {
        String s1 = "23456";
        String s2 = "1111";

        int a = 0 , b = 0;
        for (int i = 0; i < s1.length(); i++) {
            a = a * 10 + (s1.charAt(i) - '0');
        }
        for (int i = 0; i < s2.length(); i++) {
            b = b * 10 + (s2.charAt(i) - '0');
        }
        System.out.println(a*b);
    }

}

計算一句話中最後一個單詞的長度

package me.JavaStudy;

import java.util.Scanner;

public class Test3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int count = 0;
        for(int i = s.length() - 1; i >= 0; i--){
            if(s.charAt(i) == ' ')break;
            count++;
        }
        System.out.println(count);
    }
}

集合

集合和陣列的對比:

  • 長度:集合可以自由伸縮
  • 儲存型別: 陣列都可以存,集合可以存引用資料型別,存基本資料型別需要變成包裝類

ArrayList成員方法

package me.JavaStudy;

import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args){
        //1.建立ArrayList
        ArrayList<String> list = new ArrayList<>();
        System.out.println(list);
        //2.增刪改查
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        System.out.println(list);
        System.out.println("集合大小" + list.size());

        list.remove("aaa");
        System.out.println(list);
        String s = list.remove(0);
        System.out.println(s);
        System.out.println(list);

        list.set(0,"0.0");
        System.out.println(list);

        for (int i = 0; i < list.size(); i++) {
            String s2 = list.get(i);
            System.out.println(s2);
        }
    }
}

包裝類
int -> Integer
char -> Character
其他資料型別都是首字母大寫變成包裝類

package me.JavaStudy;

import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args){
        //1.建立ArrayList
        ArrayList<Integer> list1 = new ArrayList<>();

        list1.add(1);
        list1.add(2);
        System.out.println(list1);

        ArrayList<Character>list2 = new ArrayList<>();
        list2.add('a');
        list2.add('b');
        System.out.println(list2);

        ArrayList<Double> list3 = new ArrayList<>();
        list3.add(1.00213);
        list3.add(1.0001212);
        System.out.println(list3);
    }
}

ArrayList接收自定義資料型別

package Test;

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();

        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 2; i++) {
            Student s = new Student();
            System.out.println("請輸入學生姓名");
            String name = sc.next();
            System.out.println("請輸入學生年齡");
            int age = sc.nextInt();
            s.setAge(age);
            s.setName(name);
            list.add(s);
        }
        for (int i = 0; i < list.size(); i++) {
            list.get(i).showStudentInfo();
        }
    }
}

獲取價格低於3000的手機

package Test;

import java.util.ArrayList;

public class ArrayListTest2 {
    public static void main(String[] args) {
        ArrayList<Phone> list = new ArrayList<>();
        Phone p1 = new Phone("小米", 2999);
        Phone p2 = new Phone("錘子",999);
        Phone p3 = new Phone("蘋果",8999);

        list.add(p1);
        list.add(p2);
        list.add(p3);

        ArrayList<Phone> p = getPhoneInfo(list);
        for (int i = 0; i < p.size(); i++) {
            p.get(i).showPhoneInfo();
        }
    }

    public static ArrayList<Phone> getPhoneInfo(ArrayList<Phone> list){
        ArrayList<Phone> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getPrice() < 3000){
                result.add(list.get(i));
            }
        }
        return result;
    }
}

學生管理系統簡易版

package StudentSystemTest;

import java.util.ArrayList;
import java.util.Scanner;

public class StudentSystem {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Student> list = new ArrayList<>();
        while(true){
            showMenu();
            String choose = sc.next();
            switch (choose) {
                case "1" -> addStudent(list);
                case "2" -> removeStudent(list);
                case "3" -> updateStudent( list);
                case "4" -> showStudentInfo(list);
                case "5" -> {
                    System.out.println("退出");
                    System.exit(0);
                }
                default -> System.out.println("輸入有誤,請重新輸入");
            }
        }
    }

    //顯示介面
    public static void showMenu() {
        System.out.println("-------歡迎來到學生管理系統-------");
        System.out.println("1:新增學生");
        System.out.println("2:刪除學生");
        System.out.println("3:修改學生");
        System.out.println("4:查詢學生");
        System.out.println("5:退出");
        System.out.println("-----------------------------");
        System.out.println("請輸入你的選擇");
    }

    //新增學生
    public static void addStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("需要新增學生的數量");
        int count = sc.nextInt();
        for (int i = 0; i < count; i++) {
            System.out.println("輸入學生id");
            String id = sc.next();
            System.out.println("輸入學生姓名:");
            String name = sc.next();
            System.out.println("輸入學生年齡:");
            int age = sc.nextInt();
            System.out.println("輸入學生家庭住址:");
            String address = sc.next();
            Student s = new Student(id,name,age,address);
            list.add(s);
        }
        System.out.println("新增成功!");
    }

    //刪除學生
    public static void removeStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入要刪除的學生id:");
        String id = sc.next();
        boolean flag = idIsExist(list,id);
        if(flag){
            int index = getIndex(list,id);
            list.remove(index);
            System.out.println("刪除成功!");
        }
        else System.out.println("刪除失敗!,id不存在!");
    }

    //修改學生
    public static void updateStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入要修改的學生id");
        String id = sc.next();
        int index = getIndex(list,id);
        if(index > -1){
            System.out.println("輸入學生id");
            String sid = sc.next();
            list.get(index).setId(sid);
            System.out.println("輸入學生姓名:");
            String name = sc.next();
            list.get(index).setName(name);
            System.out.println("輸入學生年齡:");
            int age = sc.nextInt();
            list.get(index).setAge(age);
            System.out.println("輸入學生家庭住址:");
            String address = sc.next();
            list.get(index).setAddress(address);
            System.out.println("修改成功!");
        }
        else System.out.println("修改失敗!,id不存在!");
    }

    //查詢學生
    public static void showStudentInfo(ArrayList<Student> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).showStudentInfo();
        }
    }

    //判斷id是否存在
    public static boolean idIsExist(ArrayList<Student> list,String id){
        int index = getIndex(list,id);
        if(index > -1)return true;
        return false;
    }

    //返回id對應的索引
    public static int getIndex(ArrayList<Student> list,String id) {
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId().equals(id)){
                return i;
            }
        }
        return -1;
    }

}


學生管理系統升級版

package StudentSystemTest;

public class Student {
    private String id;
    private String name;
    private int age;
    private String address;

    public Student() {

    }

    public Student(String id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void showStudentInfo(){
        System.out.println(this.getId()+ " " + this.getName() + " "+this.getAge() + " " + this.getAddress());
    }

    /**
     * 獲取
     * @return id
     */
    public String getId() {
        return id;
    }

    /**
     * 設定
     * @param id
     */
    public void setId(String id) {
        this.id = id;
    }

}

package StudentSystemTest;

public class User {
    private String username;
    private String password;
    private String idCard;
    private String phoneNumber;

    public User() {
    }

    public User(String username, String password, String idCard, String phoneNumber) {
        this.username = username;
        this.password = password;
        this.idCard = idCard;
        this.phoneNumber = phoneNumber;
    }

    /**
     * 獲取
     * @return username
     */
    public String getUsername() {
        return username;
    }

    /**
     * 設定
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * 獲取
     * @return password
     */
    public String getPassword() {
        return password;
    }

    /**
     * 設定
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 獲取
     * @return idCard
     */
    public String getIdCard() {
        return idCard;
    }

    /**
     * 設定
     * @param idCard
     */
    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }

    /**
     * 獲取
     * @return phoneNumber
     */
    public String getPhoneNumber() {
        return phoneNumber;
    }

    /**
     * 設定
     * @param phoneNumber
     */
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

}


package StudentSystemTest;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class StudentSystem {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<User> userList = new ArrayList<>();
        loop : while(true){
            showLogin();
            String choose1 = sc.next();
            switch(choose1){
                case "1" ->
                {
                    boolean is = login(userList);
                    if(is) break loop;
                }
                case "2" -> register(userList);
                case "3" -> setPassword(userList);
                default -> System.out.println("輸入有誤,請重新輸入!");
            }
        }
        ArrayList<Student> list = new ArrayList<>();
        while(true){
            showMenu();
            String choose = sc.next();
            switch (choose) {
                case "1" -> addStudent(list);
                case "2" -> removeStudent(list);
                case "3" -> updateStudent( list);
                case "4" -> showStudentInfo(list);
                case "5" -> {
                    System.out.println("退出");
                    System.exit(0);
                }
                default -> System.out.println("輸入有誤,請重新輸入");
            }
        }
    }

    //顯示介面
    public static void showMenu() {
        System.out.println("-------歡迎來到學生管理系統-------");
        System.out.println("1:新增學生");
        System.out.println("2:刪除學生");
        System.out.println("3:修改學生");
        System.out.println("4:查詢學生");
        System.out.println("5:退出");
        System.out.println("-----------------------------");
        System.out.println("請輸入你的選擇");
    }

    //新增學生
    public static void addStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("需要新增學生的數量");
        int count = sc.nextInt();
        for (int i = 0; i < count; i++) {
            System.out.println("輸入學生id");
            String id = sc.next();
            System.out.println("輸入學生姓名:");
            String name = sc.next();
            System.out.println("輸入學生年齡:");
            int age = sc.nextInt();
            System.out.println("輸入學生家庭住址:");
            String address = sc.next();
            Student s = new Student(id,name,age,address);
            list.add(s);
        }
        System.out.println("新增成功!");
    }

    //刪除學生
    public static void removeStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入要刪除的學生id:");
        String id = sc.next();
        boolean flag = idIsExist(list,id);
        if(flag){
            int index = getIndex(list,id);
            list.remove(index);
            System.out.println("刪除成功!");
        }
        else System.out.println("刪除失敗!,id不存在!");
    }

    //修改學生
    public static void updateStudent(ArrayList<Student> list){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入要修改的學生id");
        String id = sc.next();
        int index = getIndex(list,id);
        if(index > -1){
            System.out.println("輸入學生id");
            String sid = sc.next();
            list.get(index).setId(sid);
            System.out.println("輸入學生姓名:");
            String name = sc.next();
            list.get(index).setName(name);
            System.out.println("輸入學生年齡:");
            int age = sc.nextInt();
            list.get(index).setAge(age);
            System.out.println("輸入學生家庭住址:");
            String address = sc.next();
            list.get(index).setAddress(address);
            System.out.println("修改成功!");
        }
        else System.out.println("修改失敗!,id不存在!");
    }

    //查詢學生
    public static void showStudentInfo(ArrayList<Student> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).showStudentInfo();
        }
    }

    //判斷id是否存在
    public static boolean idIsExist(ArrayList<Student> list,String id){
        int index = getIndex(list,id);
        if(index > -1)return true;
        return false;
    }

    //返回id對應的索引
    public static int getIndex(ArrayList<Student> list,String id) {
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId().equals(id)){
                return i;
            }
        }
        return -1;
    }

    //顯示登入介面
    public static void showLogin(){
        System.out.println("歡迎來到學生管理系統");
        System.out.println("請選擇操作1登入 2註冊 3忘記密碼");
        System.out.println("請輸入你的選擇:");
    }

    //登入
    public static boolean login(ArrayList<User> userList){
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入使用者名稱");
        String username = sc.next();
        int index = getUserIndex(userList,username);
        if(index > -1){
            int count = 3;
            while (count != 0) {
                System.out.println("請輸入密碼");
                String password = sc.next();
                while (true) {
                    String num = getRandomNumber();
                    System.out.println("你的驗證碼為:" + num);
                    System.out.println("請輸入驗證碼:");
                    String inputNum = sc.next();
                    if (num.equals(inputNum)) {
                        break;
                    } else System.out.println("驗證碼錯誤!請重新輸入");
                }
                if(password.equals(userList.get(index).getPassword())){
                    System.out.println("登入成功!");
                    return true;
                }
                else {
                    count--;
                    System.out.println("密碼錯誤!請重新登入");
                }
            }
            System.out.println("輸入錯誤次數達到三次!無法繼續輸入");
            return false;
        }
        else System.out.println("登陸失敗!使用者名稱不存在,請註冊後再來嘗試!");
        return false;
    }

    //註冊
    public static void register(ArrayList<User> userList){
        Scanner sc = new Scanner(System.in);
        String username , p1 ,idcard ,phoneNumber;
        while (true) {
            System.out.println("請輸入您的使用者名稱");
            username = sc.next();
            if(usernameIsTrue(userList,username)){
                break;
            }
            else System.out.println("建立失敗!");
        }
        while (true) {
            System.out.println("請輸入密碼");
            p1 = sc.next();
            System.out.println("請確認密碼");
            String p2 = sc.next();
            if(p1.equals(p2)){
                break;
            }
            else System.out.println("兩次密碼不一致!請重新輸入");
        }
        while (true) {
            System.out.println("請輸入身份證號");
            idcard = sc.next();
            if(idcardIsTrue(idcard)){
                break;
            }
            else System.out.println("身份證號不合法!請重新輸入");
        }
        while (true) {
            System.out.println("請輸入手機號");
            phoneNumber = sc.next();
            if(phoneNumberIsTrue(phoneNumber)){
                break;
            }
            else System.out.println("手機號不合法!請重新輸入");
        }
        User newUser = new User(username,p1,idcard,phoneNumber);
        userList.add(newUser);
        System.out.println("註冊成功!");
    }

    //忘記密碼
    public static void setPassword(ArrayList<User> userList){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入使用者名稱");
        String username = sc.next();
        int index = getUserIndex(userList,username);
        if(index != -1){
            System.out.println("輸入您的身份證號");
            String idcard = sc.next();
            System.out.println("輸入你的手機號");
            String phoneNumber = sc.next();
            if(userList.get(index).getIdCard().equals(idcard) && userList.get(index).getPhoneNumber().equals(phoneNumber)) {
                while (true) {
                    System.out.println("輸入新的密碼");
                    String newPassword = sc.next();
                    System.out.println("確認密碼");
                    String p = sc.next();
                    if (newPassword.equals(p)){
                        userList.get(index).setPassword(p);
                        System.out.println("修改成功!");
                        break;
                    }
                    else System.out.println("兩次輸入密碼不一致!請重新輸入");
                }
            }
            else System.out.println("身份證號或手機號輸入錯誤!");
        }
        else System.out.println("使用者不存在!");
    }

    //判斷身份證號碼是否合法
    public static boolean idcardIsTrue(String idcard){
        if(idcard.length() != 18 || idcard.charAt(0) == '0')return false;
        if(idcard.charAt(17) != 'x' && idcard.charAt(17)!='X' && idcard.charAt(17) < '0' && idcard.charAt(17) > '9'){
            return false;
        }
        for (int i = 0; i < idcard.length() - 1; i++) {
            if(idcard.charAt(i) < '0' && idcard.charAt(i) > '9')return false;
        }
        return true;
    }

    //判斷手機號是否合法
    public static boolean phoneNumberIsTrue(String phoneNumber){
       if(phoneNumber.length() != 11 || phoneNumber.charAt(0) == 0)return false;
        for (int i = 0; i < phoneNumber.length(); i++) {
            if(phoneNumber.charAt(i) < '0' || phoneNumber.charAt(i) > '9')return false;
        }
        return true;
    }

    //判斷使用者名稱是否合法
    public static boolean usernameIsTrue(ArrayList<User> userList,String username){
        if(username.length() < 3){
            System.out.println("使用者名稱太短!");
            return false;
        }
        if(username.length() > 15){
            System.out.println("使用者名稱太長!");
            return false;
        }
        if(getUserIndex(userList,username) != -1){
            System.out.println("使用者名稱已存在!");
            return false;
        }
        boolean flag1 = false , flag2 = true;
        for (int i = 0; i < username.length(); i++) {
            if(username.charAt(i) >= 'a' && username.charAt(i) <= 'z')flag1 = true;
            if(username.charAt(i) < 48 || (username.charAt(i) > 57 && username.charAt(i)<64)
        ||(username.charAt(i)>90 && username.charAt(i) < 96)||username.charAt(i)>122){
                flag2 = false;
            }
        }
        if(flag1 && flag2) return true;
        else if(flag1) System.out.println("使用者名稱含有不法字元!");
        else if(flag2) System.out.println("使用者名稱不能全為數字!");
        return false;
    }

    //返回存在使用者名稱對應的索引
    public static int getUserIndex(ArrayList<User> userList,String username){
        for (int i = 0; i < userList.size(); i++) {
            if(username.equals(userList.get(i).getUsername())){
                return i;
            }
        }
        return -1;
    }

    //生成隨機驗證碼
    public static String getRandomNumber(){
        char[] ch = new char[52];
        for (int i = 0; i < ch.length; i++) {
            if(i <= 25){
                ch[i] = (char)('a' + i);
            }
            else{
                ch[i] = (char)('A' + i - 26);
            }
        }
        StringBuilder result  = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            int randomIndex = r.nextInt(ch.length);
            result.append(ch[randomIndex]);
        }
        int randomNum = r.nextInt(10);
        result.append(randomNum);
        int randomIndex = r.nextInt(5);
        StringBuilder ans = new StringBuilder();
        int i = 0,now = 0;
        while(ans.length() != 5){
            if(now != randomIndex){
                ans.append(result.charAt(i));
                i++;
                now++;
            }
            else{
                ans.append(randomNum);
                now++;
            }
        }
        return ans.toString();
    }
}



static

static表示靜態,是Java中的一個修飾符,可以修飾成員方法,成員變數。
特點:

  • 被該類所有物件共享
  • 不屬於物件,屬於類
  • 隨著類的載入而載入,優先於物件存在

呼叫方式:

  • 類名呼叫(推薦)
  • 物件名呼叫

工具類

幫助我們做一些事情的,但是不描述任何事物的類

  • 類名見名知意
  • 私有化構造方法

一個工具類ArrayUtil

package me.JavaStudy;

public class ArrayUtil {
    private ArrayUtil() {
    }

    //列印陣列
    public static void printArr(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.println();
    }

    //求平均值
    public static double getAverage(double[] arr){
        double aver = 0.0;
        for (int i = 0; i < arr.length; i++) {
            aver += arr[i];
        }
        return aver/arr.length;
    }
}

繼承

  • java提供一個關鍵字expense。用這個關鍵詞可以讓一個類和另一個類建立繼承關係
    public class Student extends Person() {}
  • Stduent稱為子類(派生類),Person稱為父類(基類或者超類)

使用繼承的好處

  • 可以把多個子類中重複的程式碼抽取到父類中了。提高程式碼的複用性

  • 子類可以在父類的基礎上增加其他的功能,使子類更強大

  • java只支援單繼承,不支援多繼承,但支援多層繼承

  • Java所有的類都直接或間接地繼承object類

  • 子類只能訪問父類中非私有的成員

子類到底能繼承父類中的哪些內容

  1. 構造方法(非私有 不能 private 不能)
  2. 成員變數 (非私有 能 private 能)
  3. 成員方法(虛方法表 能 否則不能)

相關文章