IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java基础基本语法 流程控制、数组、面向对象练习题 -> 正文阅读

[Java知识库]Java基础基本语法 流程控制、数组、面向对象练习题

作者:token keyword

Java练习题

一、 基本语法 流程控制

1.定义整型变量 a、b,写出将 a、b 两个变量值进行互换的程序(不能使用temp变量)

public class changeTest {
    public static void main(String[] args) {
        change();
    }

    public static void change() {
        int a = 3;
        int b = 4;

        a = a + b;    // a=7
        b = a - b;    // 7-3 b=4
        a = a - b;    // 7-4 a=3
        System.out.println(a);
        System.out.println(b);
    }
}
4
3

Process finished with exit code 0

2.定义一个整型变量并赋值五位正整数作为初始值,判断是否是回文数,例如:12321 个位与万位相同 十位与千位相同。

public class huiWenTest {
    public static void main(String[] args) {
        //三元 O(1)
//        test1();

        //数组 O(n+n) O(n)
        test2();
    }

    public static void test1() {
        int num = 45654;

        int ge = num % 10;
        int shi = num / 10 % 10;
        int qian = num / 1000 % 10;
        int wan = num / 10000 % 10;

        boolean result = (ge == wan && shi == qian) ? true : false;
        System.out.println(num + "是否是回文数:" + result);
    }

    public static void test2() {

        Scanner sc = new Scanner(System.in);
        int[] num = new int[5];
        System.out.println("请输入一个五位数");
        int n = sc.nextInt();
        for (int i = num.length - 1; i >= 0; i--) {
            num[i] = n % 10;
            n /= 10;
        }
        //倒过来比较
        for (int i = 0; i < num.length / 2; i++) {
            if (num[i] != num[num.length - 1 - i]) {
                System.out.println("这个数字不是回文数");
                return;
            }
        }
        System.out.println("这个数字是回文数");
    }
}
请输入一个五位数
12321
这个数字是回文数

Process finished with exit code 0

3.定义一个整型变量并赋任意五位正整数作为初始值,输出各个位的数字之和

public class sumTest {
    public static void main(String[] args) {
        sum();
    }

    public static void sum() {
        int number = 12345;
        int ge = number % 10;
        int shi = number / 10 % 10;
        int bai = number / 100 % 10;
        int qian = number / 1000 % 10;
        int wan = number / 10000 % 10;

        System.out.println("结果为:" + (wan + qian + bai + shi + ge));
    }
}
结果为:15

Process finished with exit code 0

4.某市出租车,起步价(2 公里以内)为 8 元,超过 2 公里的按照每公里 4.5 元计算。要求根据路程计算费用。

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

        double price = 8;
        int kilometre;

        Scanner input = new Scanner(System.in);
        System.out.println("请输入您的里程:");

        if (input.hasNextInt()) {
            kilometre = input.nextInt();
            if (kilometre > 2) {
                price += (kilometre - 2) * 4.5;
                System.out.println("价格为:" + price);
            } else {
                System.out.println("价格为:" + price);
            }

        } else {
            System.out.println("你输入的数据不正确");
        }
    }
}
请输入您的里程:
10
价格为:44.0

Process finished with exit code 0

5.输入年份,判断输入的年份是否是闰年。(闰年的条件是能被 4 整除,但不能被 100 整除;或能被 400 整除。)

public class Demo02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份: ");
        int year = sc.nextInt();
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            System.out.println(year + "年是闰年");
        } else {
            System.out.println(year + "不是闰年");
        }
    }
}
请输入年份: 
2020
2020年是闰年

Process finished with exit code 0

6.要求输入月份,判断该月所处的季节并输出季节.

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

        int inputMonth;

        Scanner input = new Scanner(System.in);
        System.out.println("请输入月份(1~12):");

        if (input.hasNextInt()) {
            inputMonth = input.nextInt();
            if (inputMonth > 0 && inputMonth < 13) {
                switch (inputMonth) {
                    case 12:
                    case 1:
                    case 2:
                        System.out.println(inputMonth + "月是冬季");
                        break;
                    case 3:
                    case 4:
                    case 5:
                        System.out.println(inputMonth + "月是春季");
                        break;
                    case 6:
                    case 7:
                    case 8:
                        System.out.println(inputMonth + "月是夏季");
                        break;
                    case 9:
                    case 10:
                    case 11:
                        System.out.println(inputMonth + "月是秋季");
                        break;
                }
            } else {
                System.out.println("你输入的月份超出范围 " + inputMonth);
            }
        } else {
            System.out.println("你输入的数据有误");
        }
    }
}
请输入月份(1~12):
3
3月是春季

Process finished with exit code 0

7.根据《国家电网销售电价表》,居民生活用电按 3 个梯度收费:月用电量 150 千瓦时及以下部分,每千瓦时 0.43 元,151—400 千瓦时部分为 0.45元,401 千瓦时以上部分为 0.52 元,请编写程序,当输入用户的用电量时,计算出所需付的费用。

public class Demo04 {
    public static void main(String[] args) {
        double finalPrice;
        int electricQuantity;

        Scanner input = new Scanner(System.in);
        System.out.println("请输入您的用电量(千瓦时):");

        if (input.hasNextInt()) {

            electricQuantity = input.nextInt();

            if (electricQuantity < 0) {
                System.out.println("电表倒转");
            } else if (electricQuantity < 150) {
                finalPrice = electricQuantity * 0.43;
                System.out.println("价格为:" + finalPrice);
            } else if (electricQuantity < 400) {
                finalPrice = 150 * 0.43 + (electricQuantity - 150) * 0.45;
                System.out.println("价格为:" + finalPrice);
            } else if (electricQuantity > 400) {
                finalPrice = 150 * 0.43 + (400 - 150) * 0.45 + (electricQuantity - 400) * 0.52;
                System.out.println("价格为:" + finalPrice);
            }
        } else {
            System.out.println("你输入的数据有误");
        }
    }
}
请输入您的用电量(千瓦时)100
价格为:43.0

Process finished with exit code 0

请输入您的用电量(千瓦时)250
价格为:109.5

Process finished with exit code 0

8.商场根据会员积分打折:2000 分以内打 9 折,4000 分以内打 8 折,8000 分以内打 7.5 折,8000 分以上打 7 折, 使用 if-else-if 结构,实现手动输入购物金额和积分,计算出应缴金额。

public class Demo05 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入购物金额");
        double shop = sc.nextDouble();
        System.out.println("请输入积分");
        int score = sc.nextInt();
        if (score < 2000) {
            shop *= 0.9;
            System.out.println("目前消费" + shop + "元");
        } else if (score >= 2000 && score <= 4000) {
            shop *= 0.8;
            System.out.println("目前消费" + shop + "元");
        } else if (score <= 8000 && score > 4000) {
            shop *= 0.75;
            System.out.println("目前消费" + shop + "元");
        } else if (score > 8000) {
            shop *= 0.7;
            System.out.println("目前消费" + shop + "元");
        } else {
            System.out.println("抱歉没有折扣");
        }
    }
}
请输入购物金额
1000
请输入积分
1
目前消费900.0Process finished with exit code 0

9.一年中有 12 个月,而每个月的天数是不一样的。其中大月 31 天,分别为1,3,5,7,8,10,12 月,小月 30 天,分别 为 4,6,9,11 月。还有二月比较特殊,平年的二月只有 28 天,而闰年的二月有 29 天,由用户在控制台输入年月日,程序计算输入的日期是当年的第多少天。 (例如输入 2000 年 12 月 31 日,应该输出是第 366 天)。

public class Demo06 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入年份");
        int year = sc.nextInt();
        System.out.println("输入月份");
        int mouth = sc.nextInt();
        int sum = 0;

        for (int i = 1; i <= mouth; i++) {
            switch (i) {
                //大月
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    sum += 31;
                    break;

                //小月
                case 4:
                case 6:
                case 9:
                case 11:
                    sum += 30;
                    break;

                case 2:
                    //润年平年
                    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                        sum += 29;
                    } else
                        sum += 28;
                    break;
            }
        }
        System.out.println(year + "年" + mouth + "月" + "总天数是:" + sum);
    }
}
输入年份
2021
输入月份
12
202112月总天数是:365

Process finished with exit code 0

10.输出打印正直角三角形、倒立直角三角形、等腰三角形

public class Demo07 {
    public static void main(String[] args) {
//        test1();
        test2();
//        test3();
    }

    //正直角三角形
    public static void test1() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < i + 1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }

    //倒立直角三角形
    public static void test2() {
//        方法1
//        for (int i = 0; i < 5; i++) {
//            for (int j = 0; j < 5 - i ; j++) {
//                System.out.print("*");
//            }
//            System.out.println();

        for (int i = 0; i < 5; i++) {
            for (int j = 5; j > i; j--) {
                System.out.print("*");
            }
            System.out.println();
        }
    }

    //等腰三角形
    public static void test3() {
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >= i; j--)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print("*");
            for (int j = 1; j < i; j++)
                System.out.print("*");
            System.out.println();
        }
    }
}
*
**
***
****
*****

Process finished with exit code 0
*****
****
***
**
*

Process finished with exit code 0
     *
    ***
   *****
  *******
 *********

Process finished with exit code 0

11.打印99乘法表

public class Demo08 {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j +"*"+i + "=" + i*j + "\t");
            }
            System.out.println();
        }
    }
}
1*1=1	
1*2=2	2*2=4	
1*3=3	2*3=6	3*3=9	
1*4=4	2*4=8	3*4=12	4*4=16	
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81	

Process finished with exit code 0

12. 打印三位数中的所有水仙花数所谓“水仙花数”即一个整数满足其值等于各个数位的立方和。如: 153 是一个水仙花数,因为 153= 13+53+33

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

        int i, bai, shi, ge;
        for (i = 100; i < 1000; i++) {
            bai = i / 100;
            shi = i % 100 / 10;
            ge = i % 10;
            if (i == (int) Math.pow(bai, 3) + (int) Math.pow(shi, 3) + (int) Math.pow(ge, 3)) {
                System.out.println(i);
            }
        }
    }
}
153
370
371
407

Process finished with exit code 0

13.完成人工智障系统,输入你好吗?回复你好!,输入能听得懂嘛?回复能听得懂!…

public class Demo10 {
    public static void main(String[] args) {
        //获取输入
        Scanner sc = new Scanner(System.in);
        //变量声明类型
        String question;
        while(true){
            //输入数据赋值给question
            question = sc.next();
            //replace()方法选词替换 参数一个是要替换的字符串 一个是新的字符串
            question = question.replace("吗","");
            question = question.replace("我","我也");
            question = question.replace("?","!");
            //输出
            System.out.println(question);
        }
    }
}
你好吗?
你好!
听得懂吗?
听得懂!
你好
你好


Process finished with exit code 0

二、数组

1. 定义一个长度为 10 的整型数组 nums ,循环输入 10 个整数。 然后将输入一个整数,查找此整数,找到 输出下标, 没找到给出提示。

public class Demo01 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] nums = new int[10];
        System.out.println("请输入10个整数");
        for (int i = 0; i < nums.length; i++) {
            nums[i] = input.nextInt();
        }

        //要查找的数
        System.out.println("请输入要查找的整数");
        int findNum = input.nextInt();

        //查找
        for (int i = 0; i < nums.length; i++) {
            if (findNum == nums[i]) {
                System.out.println("查找的整数下标是:" + i);
                break;
            } else if (i == nums.length - 1) {
                System.out.println("没有找到该整数");
            }
        }
    }
}

2.定义一个长度为 10 的整型数组 nums ,循环输入 10 个整数。输出数组的最大值、最小值。

public class Demo02 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] nums = new int[10];
        System.out.println("请输入10个整数");
        for (int i = 0; i < nums.length; i++) {
            nums[i] = input.nextInt();
        }

        int max = nums[0];
        int min = nums[0];

        for (int i = 0; i < nums.length; i++) {
            if (max < nums[i]) {
                max = nums[i];
            }
            if (min > nums[i]) {
                min = nums[i];
            }
        }
        System.out.println("最大值为:" + max + ",最小值为:" + min);
    }
}

3.给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并输出他们的数组下标假设每种输入只会对应一个答案,不能重复利用这个数组中同样的元素。

public class Demo03 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        boolean flag = false;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    System.out.println("找到了满足条件的两个数:" + nums[i] + "--" + nums[j] + "下标是:" + i + "--" + j);
                }
            }
        }
    }
}

4.对数组{1,3,9,5,6,7,15,4,8}进行排序,然后使用二分查找元素6,并输出排序后的下标。

public class Demo04 {
    public static void main(String[] args) {
        //排序并查找
        int[] a = {1, 3, 9, 5, 6, 7, 15, 4, 8};
        //储存最大值
        int temp;
        //用冒泡排序对输入的数字进行排序处理
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - i - 1; j++) {
                if (a[j] > a[j + 1]) {
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }

        int f = 6;

        //利用二分查找
        //最小边界下标
        int minIndex = a[0];
        //最大边界下标
        int maxIndex = a.length - 1;
        //中间下标
        int centerIndex = (maxIndex + minIndex) / 2;
        while (true) {
            if (a[centerIndex] > f) {
                //如果中间数据较大,最大范围下标=centerIndex-1
                maxIndex = centerIndex - 1;
            } else if (a[centerIndex] < f) {
                //如果中间数据较小,最小范围下标=centerIndex+1
                minIndex = centerIndex + 1;
            } else {
                //如果中间数据相等,输出中间下标
                break;
            }

            if (minIndex > maxIndex) {
                centerIndex = -1;
                System.out.println("你查找的数不存在");
            }
            //当边界更新时,需要更新中间下标
            centerIndex = (maxIndex + minIndex) / 2;
        }
        System.out.println("6的下标为" + centerIndex);
    }
}

5. 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。示例:输入: [0,1,0,3,12] 输出: [1,3,12,0,0]

public class Demo05 {
    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 3, 12};

        int[] newNums = moveZero(nums);

        for (int i = 0; i < newNums.length; i++) {
            System.out.println(newNums[i]);
        }
    }

    public static int[] moveZero(int[] nums) {
        int index1 = 0;
        int index2 = 0;
        //索引二没有超出数组长度
        while (index2 < nums.length) {
            //索引二扫描的元素不为0就往前面移动
            if (nums[index2] != 0) {
                nums[index1] = nums[index2];
                index1++;
                index2++;
                
                //为0就让索引一接着继续扫描
            } else {
                index2++;
            }
        }
        //补零
        for (int i = index1; i < nums.length; i++) {
            nums[i] = 0;
        }
        return nums;
    }
}

三、面向对象

1.编写 Car 类,属性有品牌(brand)和颜色(Color),定义 show 方法

public class Demo01 {
    public static void main(String[] args) {
        Car car = new Car();
        car.brand = "BMW";
        car.Color = "白色";
        car.show();
    }
}

class Car {
    String brand;
    String Color;

    void show() {
        System.out.println("车的品牌是:" + brand + ", 颜色是" + Color);
    }
}

2.定义一个游戏类,包括游戏的属性包括:游戏名,类型,大小,星级,介绍等,可以调用方法输出游戏的介绍.

public class Demo02 {
    public static void main(String[] args) {
        Game game = new Game();
        game.name = "LOL";
        game.type = "5v5";
        game.size = "30g";
        game.starLevel = "5星";

        //介绍
        game.show();
    }
}
class Game {
    String name;
    String type;
    String size;
    String starLevel;

    void show() {
        System.out.println(" 游戏的名称是:" + name + " 类型是:" + type + " 大小是" + size + " 星级是:" + starLevel);
    }
}

3. 定义并测试一个代表员工的 Employee 类。它的属性包括“员工姓名”、“员工号码”、“员工基本薪水”、“员工薪水增长率”;他的方法包括“构造方法”、“获取员工姓名”、“获取员工号码”、“获取员工基本薪水”、“计算薪水增长额”及“计算增长后的工资总额”。

public class Demo03 {
    public static void main(String args[]) {
        Employee emp = null;
        emp = new Employee();
        emp.number = "001";
        emp.name = "张三";
        emp.salary = 1000;
        emp.time = 5;
        emp.increase();
        emp.total();
    }

}
class Employee {
    String number;
    String name;
    float salary;
    float time;

    //增长率
    public void increase() {
        System.out.println("增长额=" + "工作年限*" + 200);
        System.out.println("增长额为" + time * 200);
    }

    //工资总额
    public void total() {
        System.out.println("工资总数=基本工资+增长额");
        System.out.println(salary + time * 200);
    }
}

4.具有属性: 名称(title)、页数(pageNum),其中页数不能少于 200 页,否则输出错误信息,并赋予默认值 200。具有方法: 为各属性设置赋值和取值方法。 detail,用来在控制台输出每本图书的名称和页数编写测试类 BookTest 进行测试:为 Demo01.Book 对象的属性赋予初始值,并调用 Demo01.Book 对象的 detail 方法,看看输出是否正确。

public class Book {
    //名称
    private String title;
    //页数
    private int pageNum;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        if (pageNum < 200) {
            this.pageNum = 200;
            System.err.println("页面赋值数需要大于200 已经赋值为默认200");
            return;
        }
    }

    //详细方法
    public void detail() {
        System.out.println("图书名称是:" + title);
        System.out.println("页数名称是:" + pageNum);
    }
}
public class BookTest {
    public static void main(String[] args) {
        Book book = new Book();
        book.setTitle("计算机");
        book.setPageNum(100);

        //展示方法
        book.detail();
    }
}
页面赋值数需要大于200 已经赋值为默认200
图书名称是:计算机
页数名称是:200

Process finished with exit code 0

5.通过类描述衣服, 每个衣服对象创建时需要自动生成一个序号值。 要求:每个衣服的序号是不同的, 且是依次递增 1 的。

public class Clothes {
    private int clothId;
    private static int num = 1000;

    //自增
    public Clothes() {
        clothId = num;
        num++;
    }

    public int getClothId() {
        return clothId;
    }
}
public class ClothesTest {
    public static void main(String[] args) {
        Clothes clothes1 = new Clothes();
        Clothes clothes2 = new Clothes();
        Clothes clothes3 = new Clothes();

        System.out.println(clothes1.getClothId());
        System.out.println(clothes2.getClothId());
        System.out.println(clothes3.getClothId());
    }
}
1000
1001
1002

Process finished with exit code 0

6. 通过类描述Java 学员。具有属性: 姓名,年龄,性别,爱好,公司(都是:开课吧),学科(都是:Java 学科)。思考:请结合 static 修饰属性进行更好的类设计。

public class Student {

    private String name;
    private int age;
    private String sex;
    private String hobby;

    public static String company;
    public static String subject;

    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 getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getHobby() {
        return hobby;
    }

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


    public void show() {
        System.out.println("姓名是:" + name + " 年龄是:" + age + " 性别是" + age + " 爱好是" + hobby);
        System.out.println("公司是:" + company + " 学科是:" + subject);
    }
}
public class StudentTest {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("张三");
        student.setAge(18);
        student.setSex("男");
        student.setHobby("篮球");

        Student.company = "JAVA公司";
        Student.subject = "java";

        Student student1 = new Student();
        student1.setName("李四");
        student1.setAge(20);
        student1.setSex("女");
        student1.setHobby("排球");

        student.show();
        student1.show();
    }
}
姓名是:张三 年龄是:18 性别是18 爱好是篮球
公司是:JAVA公司 学科是:java
姓名是:李四 年龄是:20 性别是20 爱好是排球
公司是:JAVA公司 学科是:java

Process finished with exit code 0

7.猜拳游戏:

  1. 定义机器类,以及拳头属性(此属性只有三个值:剪刀,石头,布。这里的值可以使用数值代替)
  2. 定义生成随机数的方法(让机器生成剪刀,石头,布的值),赋值给第一步的拳头属性
  3. 定义测试类,获取用户输入的剪头石头布的值,和随机生成的值比较
  4. 测试中,定义变量保存胜者积分
/**
 * 用户类
 * @author: JunLog
 */
public class User {
    static Scanner input = new Scanner(System.in);
    int user = 0;//用户出拳
    int score = 0;//用户积分
    int num = 0;//对战局数

    public int setUser() {

        System.out.println("请输入:1.剪刀 2.石头 3.布");
        user = input.nextInt();
        
        if (user == 1) {
            System.out.println("用户出拳:剪刀");
        } else if (user == 2) {
            System.out.println("用户出拳:石头");
        } else if (user == 3) {
            System.out.println("用户出拳:布");
        }
        return user;
    }
}

/**
 * 机器类
 * @author: JunLog
 */
public class Robot {
    int id = 0;//获得机器人的出手
    int score = 0;//机器人的积分

    //获得机器人的出拳
    public int setId() {

        Random random = new Random();
        int r = random.nextInt(3);
        //获取机器人随机出拳 +1是因为random区间不包括3 是0-2 
        id = r + 1;
        
        if (id == 1) {
            System.out.println("机器人出拳:剪刀");
        } else if (id == 2) {
            System.out.println("机器人出拳:石头");
        } else if (id == 3) {
            System.out.println("机器人出拳:布");
        }
        return id;
    }
}
/**
 * 游戏开始类
 * 初始化用户、机器类 初始化游戏开始对战 做游戏判断
 * @author: JunLog
 */
public class Game {

    User user = new User();
    Robot robot = new Robot();

    /**
     * 游戏开始
     */
    public void GameStart() {
        System.out.println("------- 猜拳游戏 --------");
        System.out.println("--- 1-剪刀 2-石头 3-布--- ");

        judge();

        showResult();
    }

    /**
     * 输赢加分判断
     */
    private void judge() {

        Scanner input = new Scanner(System.in);
        System.out.println("输入对战局数");
        user.num = input.nextInt();
        System.out.println("------- 游戏开始 --------");

        //初始化第一次出拳
        int userFirst;
        int robotFirst;

        for (int i = 0; i < user.num; i++) {
            //获取双方出拳
            userFirst = user.setUser();
            robotFirst = robot.setId();

            //判断
            if (userFirst == robotFirst) {
                System.out.println("平局 积分不变");
            } else if ((userFirst == 2) && (robotFirst == 1) || (userFirst == 3 && robotFirst == 2) ||
                    (userFirst == 1) && (robotFirst == 3)) {
                System.out.println("你赢了 加一分");
                user.score++;
            } else {
                System.out.println("你输了 机器人加一分");
                robot.score++;
            }
        }
    }

    /**
     * 结果显示
     */
    private void showResult() {
        //显示对战次数
        System.out.println("------------------------------");
        System.out.println("对战次数:" + user.num);
        //显示最终得分
        System.out.println("\n姓名\t得分");
        System.out.println("用户" + "\t" + user.score);
        System.out.println("机器人" + "\t" + robot.score + "\n");
        System.out.println("================================");

        if (user.score == robot.score) {
            System.out.println("结果:打成平手。");
        } else if (user.score > robot.score) {
            System.out.println("你赢了!");
        } else {
            System.out.println("你输了");
        }
        System.out.println("游戏结束");
        System.out.println("--------------------------");
    }
}
/**
 * 测试类
 * @author: JunLog
 */
public class GameTest {
    public static void main(String[] args) {
        Game game = new Game();
        game.GameStart();
    }
}
------- 猜拳游戏 --------
--- 1-剪刀 2-石头 3---- 
输入对战局数
1
------- 游戏开始 --------
请输入:1.剪刀 2.石头 3.1
用户出拳:剪刀
机器人出拳:布
你赢了 加一分
------------------------------
对战次数:1

姓名	得分
用户	1
机器人	0

================================
你赢了!
游戏结束
--------------------------

Process finished with exit code 0


8.假设用户账号为:admin,密码为 123,编写用户登陆案例。 要求:请将登陆定义为 login 方法, 并将 login 方法写在 UserService 类中。

public class UserService {

    //用户登录
    public boolean login(String userName, String password){
        if ("admin".equals(userName) && "123".equals(password)){
            return true;
        }
        return false;
    }
}
/**
 * 测试用户登录
 * @author: JunLog
 */
public class UserServiceTest {
    public static void main(String[] args) {
        UserService userService = new UserService();

        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名和密码");
        String userName = input.next();
        String password = input.next();

        boolean result = userService.login(userName, password);
        if (result) {
            System.out.println("登录成功");
        } else {
            System.out.println("登录失败! 用户名或密码错误");
        }
    }
}
请输入用户名和密码
ad
1
登录失败! 用户名或密码错误

Process finished with exit code 0

请输入用户名和密码
admin
123
登录成功

Process finished with exit code 0

9. 自定义一个类, 命名为 MyList,类中包含属性:Object[] element;定义如下几个方法:

  1. 增加方法 add : 可以向数组属性中依次存储 Object,数组内容存满时,需实现动态扩容(详解在下面)。参考: Boolean add(Objectobj)
  2. 删除方法 remove : 可以根据数据或下标,从数组属性中删除 Object 数据,删除后,数组后续 元素需前移。参考:void remove(Object obj) 或 void remove(Integer index)
  3. 查询方法 get : 方法传入下标,返回数组中指定下标的数据。参考:Object get(Integer index)
  4. 当前存储数据量 size : 获取当前存储的有效数据长度参考:size=数组.length动态扩容详解:无需真正增加原数组的容量,只用将原内容复制到新的大数组,然后让原数组名称重新等于大数组即 可。由于原数组数据在堆中, 失去引用会被 GC 自动回收。(考点:如何实现数组的动态长度)。
public class MyList {
    private Object[] element;
    private int capacity;       //容量
    private int size;           //实际大小

    public MyList() {
        size = 0;
        capacity = 4;
        //分配数组的空间
        element = new Object[capacity];
    }

    /**
     * 根据指定的对象删除
     * @param obj
     * @return
     */
    public Object remove(Object obj){
        for (int i = 0; i < element.length; i++) {
            if (element[i]!=null && obj == element[i]){
                return remove(i);
            }
        }
        //没有要删除的对象
        return null;
    }

    /**
     * 根据下标删除
     * @param index
     * @return
     */
    public Object remove(int index){
        if (index == size-1){
            size--;
            return element[index];
        }
        Object obj = element[index];
        for (int i = index; i < size; i++) {
            element[i] = element[i+1];
        }
        size--;
        return obj;
    }

    /**
     * 查询方法
     * @param index
     * @return
     */
    public Object get(int index){
        return element[index];
    }

    /**
     * 添加元素
     * @param obj
     */
    public void add(Object obj) {
        //判断数组内容是否存满
        if (size >= capacity) {
            //扩容
            Object[] newArr = new Object[capacity * 2];
            //将原有数组的元素复制到新的数组中
            for (int i = 0; i < element.length; i++) {
                newArr[i] = element[i];
            }
            //原数组名重洗等于新数组
            element = newArr;
        }
        element[size] = obj;
        size++;
    }

    public int getSize() {
        return size;
    }
}
/**
 * 测试
 * @author: JunLog
 */
public class MyListTest {
    public static void main(String[] args) {
        MyList list = new MyList();

        for (int i = 0; i < 6; i++) {
            list.add("java" + i);
        }

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

        Object obj = list.remove(2);
        System.out.println("删除元素是:" + obj);
    }
}

java0
java1
java2
java3
java4
java5
删除元素是:java2

Process finished with exit code 0
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-08-22 13:25:07  更:2021-08-22 13:25:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 21:17:41-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码