Java基礎 --- 物件導向綜合訓練

Y423x發表於2024-03-19

物件導向綜合訓練


案例一:文字版格鬥遊戲

格鬥遊戲,每個遊戲角色的姓名,血量,都不相同,在選定人物的時候(new物件的時候),這些資訊就應該被確定下來。

補充:

public class Test {
    public static void main(String[] args) {
        //兩部分引數
        //第一部分引數:要輸出的內容%s(佔位)
        //第二部分引數:填充的資料
        System.out.printf("你好啊%s","張三");
        System.out.println();//printf無法換行,這裡做換行處理
        System.out.printf("%s你好啊%s","張三","李四");
    }
}

正題:

import java.util.Random;

public class Role {
    private String name;
    private int blood;
    private char gender;
    private String face;//長相是隨機的

    String[] boyfaces = {"風流俊雅","器宇軒昂","相貌英俊","五官端正","相貌平平","一塌糊塗","面目猙獰"};
    String[] girlfaces = {"美奐絕倫","沉魚落雁","亭亭玉立","身材姣好","相貌平平","相貌簡陋","慘不忍睹"};

    //attack攻擊描述:
    String[] attacks_desc={
            "%s使出了一招【背心釘】,轉到對方的身後,一掌向%s背心的靈臺穴拍去。",
            "%s使出了一招【遊空探爪】,飛起身形自半空中變掌為抓鎖向%s。",
            "%s大喝一聲,身形下伏,一招【劈雷墜地】,捶向%s雙腿。",
            "%s運氣於掌,一瞬間掌心變得血紅,一式 【掌心雷】,推向%s。",
            "%s陰手翻起陽手跟進,一招【沒遮攔】,結結實實的捶向%s。",
            "%s上步搶身,招中套招,一招【劈掛連環】,連環攻向%s。"
    };

    //injured受傷描述:
    String[] injureds_desc={
            "結果%s退了半步,毫髮無損",
            "結果給%s造成一處瘀傷",
            "結果一擊命中,%s痛得彎下腰",
            "結果%s痛苦地悶哼了一聲,顯然受了點內傷",
            "結果%s搖搖晃晃,一跤摔倒在地",
            "結果%s臉色一下變得慘白,連退了好幾步",
            "結果【轟】的一一聲,%s口中鮮血狂噴而出",
            "結果%s一聲慘叫,像灘軟泥般塌了下去"
    };

    public Role(){
    }

    public Role(String name,int blood,char gender){
        this.name = name;
        this.blood = blood;
        this.gender = gender;
        //隨機長相
        setFace(gender);
    }

    public char getGender(){
        return gender;
    }

    public void setGender(char gender){
        this.gender = gender;
    }

    public String getFace(){
        return face;
    }

    public void setFace(char gender){
        Random r = new Random();
        //長相是隨機的
        if(gender == '男'){
            //從boyfaces裡面隨機
            int index = r.nextInt(boyfaces.length);
            this.face = boyfaces[index];
        } else if (gender == '女') {
            //從girlfaces裡面隨機
            int index = r.nextInt(girlfaces.length);
            this.face = girlfaces[index];
        }else{
            this.face = "相貌平平";
        }
    }

    public String getName(){
        return name;
    }

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

    public int getBlood(){
        return blood;
    }

    public void setBlood(int blood){
        this.blood = blood;
    }

    //定義一個方法用於攻擊別人
    //方法的呼叫者去攻擊引數
    public void attack(Role role){
        Random r = new Random();
        int index = r.nextInt(attacks_desc.length);
        String KungFu = attacks_desc[index];
        //輸出一個攻擊的效果
        System.out.printf(KungFu,this.getName(),role.getName());
        System.out.println();
        //計算造成的傷害1 ~ 20
        int hurt = r.nextInt(1,21);
        //修改一下捱揍的人的血量
        //剩餘血量
        int remainBlood = role.getBlood() - hurt;
        //對剩餘血量做一個驗證,如果為負數了,就修改為0
        remainBlood = remainBlood < 0 ? 0 : remainBlood;
        //修改一下捱揍的人的血量
        role.setBlood(remainBlood);

        //受傷的描述
        //血量>90 0索引的描述
        //80 ~ 90 1索引的描述
        //70 ~ 80 2索引的描述
        //60 ~ 70 3索引的描述
        //40 ~ 60 4索引的描述
        //20 ~ 40 5索引的描述
        //10 ~ 20 6索引的描述
        //小於10的 7索引的描述
        if(remainBlood > 90){
            System.out.printf(injureds_desc[0],role.getName());
        } else if (remainBlood > 80 && remainBlood <= 90) {
            System.out.printf(injureds_desc[1],role.getName());
        } else if (remainBlood > 70 && remainBlood <= 80) {
            System.out.printf(injureds_desc[2],role.getName());
        } else if (remainBlood > 60 && remainBlood <= 70) {
            System.out.printf(injureds_desc[3],role.getName());
        } else if (remainBlood > 40 && remainBlood <= 60) {
            System.out.printf(injureds_desc[4],role.getName());
        } else if (remainBlood > 20 && remainBlood <= 40) {
            System.out.printf(injureds_desc[5],role.getName());
        } else if (remainBlood > 10 && remainBlood <= 20) {
            System.out.printf(injureds_desc[6],role.getName());
        } else {
            System.out.printf(injureds_desc[7],role.getName());
        }
        System.out.println();
    }

    public void showRoleInfo(){
        System.out.println("姓名為" + getName());
        System.out.println("血量:" + getBlood());
        System.out.println("性別:" + getGender());
        System.out.println("長相" + getFace());
    }
}

public class GameTest {
    public static void main(String[] args) {
        //1.建立第一個角色
        Role r1 = new Role("炎拳", 100,'男');
        //2.建立第二個角色
        Role r2 = new Role("巳蛇",100,'女');
        
        //展示一下角色的資訊
        r1.showRoleInfo();
        r2.showRoleInfo();
        //3.開始格鬥
        while(true){
            //r1開始攻擊r2
            r1.attack(r2);
            //判斷r2的剩餘血量
            if(r2.getBlood() == 0){
                System.out.println(r1.getName() + "K.O了" + r2.getName());
                break;
            }
            //r2攻擊r1
            r2.attack(r1);
            if(r1.getBlood() == 0){
                System.out.println(r2.getName() + "K.O了" + r1.getName());
                break;
            }
        }
    }
}

案例二:物件陣列練習


物件陣列1

定義陣列儲存3個商品物件。

商品的屬性:商品的id,名字,價格,庫存。

常見三個商品物件,並把商品物件存入到陣列當中。

public class Goods {
    private String id;
    private String name;
    private double price;
    private int count;

    public Goods(){
    }

    public Goods(String id,String name,double price,int count){
        this.id = id;
        this.name = name;
        this.price = price;
        this.count = count;
    }

    public String getId(){
        return id;
    }

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

    public String getName(){
        return name;
    }

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

    public double getPrice(){
        return price;
    }

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

    public int getCount(){
        return count;
    }

    public void setCount(int count){
        this.count = count;
    }
}

class GoodsTest {
    public static void main(String[] args) {
        //1.建立陣列
        Goods[] arr = new Goods[3];

        //2.建立三個商品物件
        Goods g1 = new Goods("114514","華為P60",6999.9,100);
        Goods g2 = new Goods("10086","燒水壺",248.0,58);
        Goods g3 = new Goods("404","帕魯",555.5,1234);

        //3.把商品新增到陣列裡
        arr[0] = g1;
        arr[1] = g2;
        arr[2] = g3;

        //4.遍歷
        for (int i = 0; i < arr.length; i++) {
            Goods goods = arr[i];
            System.out.println(goods.getId() + "," + goods.getName() + "," + goods.getPrice() + "," + goods.getCount());
        }
    }
}

物件陣列2

定義陣列循序3部汽車物件。

汽車的屬性:品牌,價格,顏色。

建立三個汽車物件,資料透過鍵盤錄入而來,並把資料存入到陣列當中。

補充:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        //鍵盤錄入
        //第一套體系:
        //nextInt();接收整數
        //nextDouble();接收小數
        //next();接收字串
        //遇到空格,製表符,回車就停止接收,這些符號後面的資料就不會接收了

        //第二套體系:
        //nextLine();接收字串
        //可以接受空格,製表符,遇到回車才停止接收資料
        
        //鍵盤錄入的兩套體系不能混用
        //弊端:先用nextInt,再用nextLine會導致下面的nextLine接收不到資料

        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入一個整數");
        int num1 = sc.nextInt();//123 1
        System.out.println(num1);//123
        System.out.println("請輸入第二個整數");
        int num2 = sc.nextInt();
        System.out.println(num2);//1

        System.out.println("請輸入一個字串");
        String str1 = sc.next();//abc a
        System.out.println(str1);//abc
        System.out.println("請輸入第二個字串");
        String str2 = sc.next();
        System.out.println(str2);//a

        System.out.println("請輸入一個字串");
        String line1 = sc.nextLine();
        System.out.println(line1);
        System.out.println("請輸入二個字串");
        String line2 = sc.nextLine();
        System.out.println(line2);
    }
}

正題:

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

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("請輸入汽車的價格");
            int price = sc.nextInt();//錄入價格
            c.setPrice(price);
            System.out.println("請輸入汽車的顏色");
            String color = sc.next();//錄入顏色
            c.setColor(color);
            arr[i] = c;//把汽車物件新增到陣列當中
        }
        for (int i = 0; i < arr.length; i++) {
            Car car = arr[i];
            System.out.println(car.getBrand() + "," + car.getPrice() + "," + car.getColor());
        }
    }
}

物件陣列3

定義陣列儲存3部手機物件。

手機的屬性:品牌,價格,顏色。

要求,計算出三部手機的平均價格。

public class Phone {
    private String brand;//品牌
    private int price;//價格
    private String color;//顏色

    public Phone(){
    }

    public Phone(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 class PhoneTest {
    public static void main(String[] args) {
        //建立一個陣列
        Phone[] arr = new Phone[3];
        //建立手機的物件
        Phone p1 = new Phone("鴨梨",2999,"白色");
        Phone p2 = new Phone("菠蘿",3100,"黃色");
        Phone p3 = new Phone("大哥大",1000,"紅色");
        //把手機物件新增到陣列當中
        arr[0] = p1;
        arr[1] = p2;
        arr[2] = p3;
        //獲取散步手機的平均價格
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            Phone phone = arr[i];
            sum += phone.getPrice();
        }
        //求平均值
        int avg = sum / arr.length;
        System.out.println(avg);
    }
}

物件陣列4

定義陣列儲存4個女朋友的物件

女朋友的屬性:姓名、年齡、性別、愛好

要求1:計算出四女朋友的平均年齡

要求2:統計年齡比平均值低的女朋友有幾個?並把她們的所有資訊列印出來。

public class GirlFriend {
    private String name;//姓名
    private int age;//年齡
    private String gender;//性別
    private String hobby;//愛好

    public GirlFriend(){
    }

    public GirlFriend(String name,int age,String gender,String hobby){
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.hobby = hobby;
    }

    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 getGender(){
        return gender;
    }

    public void setGender(String gender){
        this.gender = gender;
    }

    public String GetHobby (){
        return hobby;
    }

    public void setHobby (String hobby){
        this.hobby = hobby;
    }
}

public class GirlFriendTest {
    public static void main(String[] args) {
        GirlFriend[] arr = new GirlFriend[4];
        GirlFriend g1 = new GirlFriend("柳如煙",18,"女","逛街");
        GirlFriend g2 = new GirlFriend("沈江雪",25,"女","醫學");
        GirlFriend g3 = new GirlFriend("慕容雪",21,"女","書法");
        GirlFriend g4 = new GirlFriend("唐嫣",17,"女","繪畫");
        arr[0] = g1;
        arr[1] = g2;
        arr[2] = g3;
        arr[3] = g4;
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            GirlFriend girlFriend = arr[i];
            sum += girlFriend.getAge();
        }
        int avg = sum / arr.length;
        System.out.println(avg);
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            GirlFriend girlFriend = arr[i];
            if(girlFriend.getAge() < avg){
                count++;
                System.out.println(girlFriend.getName() + "," + girlFriend.getAge() + "," + girlFriend.getGender() + "," + girlFriend.GetHobby());
            }
        }
        System.out.println(count);
    }
}

物件陣列5

定義一個長度為3的陣列,陣列儲存1~3名學生物件作為初始資料,學生物件的學號,姓名各不相同。

學生的屬性:學號,姓名,年齡。

要求1:再次新增一一個學生物件,並在新增的時候進行學號的唯一性判斷。

要求2:新增完畢之後,遍歷所有學生資訊。

要求3:透過id刪除學生資訊

​ 如果存在,則刪除,如果不存在,則提示刪除失敗。

要求4:刪除完畢之後,遍歷所有學生資訊。

要求5:查詢陣列id為"2” 的學生,如果存在,則將他的年齡+1歲


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

要求1~要求2:

public class Test {
    public static void main(String[] args) {
        //建立陣列,儲存學生物件
        Student[] arr = new Student[3];
        //建立學生物件,新增到陣列當中
        Student stu1 = new Student(1,"張三",18);
        Student stu2 = new Student(2,"李四",23);
        Student stu3 = new Student(3,"王五",20);
        //把學生物件新增到陣列當中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;
        Student stu4 = new Student(4,"趙六",24);
        //唯一性判斷
        //已存在 --- 不用新增
        //不存在 --- 新增
        boolean flag = contains(arr,stu4.getId());
        if(flag){
            //id存在
            System.out.println("當前id重複,請修改id後再重新新增");
        }else {
            //id不存在
            //把stu4新增到陣列當中
            //1.陣列已經存滿 --- 建立一個新的陣列,新陣列的長度 = 老陣列的長度 + 1
            //2.陣列沒有存滿 --- 直接新增
            int count = getCount(arr);
            if(count == arr.length){
                //存滿
                //建立一個新的陣列,新陣列的長度 = 老陣列的長度 + 1
                Student[] newArr = creatNewArr(arr);
                newArr[count] = stu4;
                printArr(newArr);
            }else {
                //未存滿
                arr[count] = stu4;
                printArr(arr);
            }
        }
    }
    public static void printArr(Student[] arr){//定義方法遍歷陣列
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                System.out.println(stu.getId() + "," + stu.getName() + "," + stu.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;
    }

    public static int getCount(Student[] arr){//定義方法,判斷陣列中存了幾個元素
        int count = 0;//計數器
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != null){
                count++;
            }
        }
        return count;
    }

    public static boolean contains(Student[] arr,int id){//定義方法,判斷id是否存在
        for (int i = 0; i < arr.length; i++) {
            //獲取陣列中每一個學生物件
            Student stu = arr[i];
            if(stu != null){
                //獲取陣列中學生物件的id
                int sid = stu.getId();
                if(sid == id){
                    return true;
                }
            }
        }
        return false;
    }
}

要求3~要求4:

public class Test1 {
    public static void main(String[] args) {
        //建立陣列,儲存學生物件
        Student[] arr = new Student[3];
        //建立學生物件,新增到陣列當中
        Student stu1 = new Student(1, "張三", 18);
        Student stu2 = new Student(2, "李四", 23);
        Student stu3 = new Student(3, "王五", 20);
        //把學生物件新增到陣列當中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;
        int index = getIndex(arr,2);
        if(index >= 0){
            //存在,刪除
            arr[index] = null;
            printArr(arr);
        }else {
            //不存在,刪除失敗
            System.out.println("當前id不存在,刪除失敗!");
        }
    }

    public static void printArr(Student[] arr){//定義方法遍歷陣列
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                System.out.println(stu.getId() + "," + stu.getName() + "," + stu.getAge());
            }
        }
    }

    public static int getIndex(Student[] arr,int id){//找到id在陣列中的索引
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                int sid = stu.getId();
                if(sid == id){
                    return i;
                }
            }
        }
        return -1;
    }
}

要求5:

public class Test2 {
    public static void main(String[] args) {
        //建立陣列,儲存學生物件
        Student[] arr = new Student[3];
        //建立學生物件,新增到陣列當中
        Student stu1 = new Student(1, "張三", 18);
        Student stu2 = new Student(2, "李四", 23);
        Student stu3 = new Student(3, "王五", 20);
        //把學生物件新增到陣列當中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;
        int index = getIndex(arr,2);
        if(index >= 0){
            //存在,年齡+1
            Student stu = arr[index];
            int newAge = stu.getAge() + 1;
            stu.setAge(newAge);
            printArr(arr);
        }else {
            //不存在,直接提示
            System.out.println("當前id不存在,修改失敗!");
        }
    }

    public static void printArr(Student[] arr){//定義方法遍歷陣列
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                System.out.println(stu.getId() + "," + stu.getName() + "," + stu.getAge());
            }
        }
    }

    public static int getIndex(Student[] arr,int id){//找到id在陣列中的索引
        for (int i = 0; i < arr.length; i++) {
            Student stu = arr[i];
            if(stu != null){
                int sid = stu.getId();
                if(sid == id){
                    return i;
                }
            }
        }
        return -1;
    }
}

相關文章