目录
面向对象
1、面向对象介绍
⭐️面向对象介绍:
- 面向:拿、找
- 对象:能干活的东西
- 面向对象编程:拿东西过来做对应的事情
面向对象编程的例子:
(想做对应的事情,就要找对应的东西来解决。)
❓为什么用面向对象编程?
在现实生活中想做什么都是找一个个东西来解决的,在程序中要干什么其实也是找一个个东西来解决的,这种方式更符合人类思维习惯,编程更简单,更好理解。
❓面向对象编程到底学什么?
- 学习获取已有对象并使用
- 学习如何自己设计对象并使用
面向对象的语法。
2、类和对象
2.1 类和对象
对象就是能够帮助我们解决问题一个又一个的东西,但是这些东西不是凭空出现的,造对象的时候是要根据设计图才能造出来的。
⭐️类和对象
- 类(设计图):是对象共同特征的描述;
- 对象:是真实存在的具体东西。
在Java中,必须先设计类,才能获得对象。
⭐️如何定义类
⭐️如何得到类的对象
⭐️如何使用对象
2.2 类的几个补充注意事项
定义类的补充注意事项
-
用来描述一类事物的类,专业叫做:Javabean类。
在Javabean类中,是不写main方法的。 -
在以前,编写main方法的类,叫做测试类。
我们可以在测试类中创建iavabean类的对象并进行赋值调用 -
类名首字母建议大写,需要见名知意,驼峰模式。
-
一个ava文件中可以定义多个class类,且只能一个类是public修饰,而且public修饰的类名必须成为代码文件名。
实际开发中建议还是一个文件定义一个class类。 -
成员变量的完整定义格式是:修饰符 数据类型 变量名称=初始化值;一般无需指定初始化值,存在默认值。
-
3、封装
3.1 封装概述
封装概述:
是面向对象三大特征之一(封装,继承,多态)。
对象代表什么,就得封装对应的数据,并提供数据对应的行为
🌰
1️⃣(人画圆,圆是圆自己画的,人只是调用了 圆的方法 去画这个圆。所以 画圆 这个方法应该设计到 圆 里面。)
2️⃣
(人关门,门是自己关的,人只是给了门一个作用力,门就自己关起来了。所以 关门 这个方法是门的方法而不是人的方法。)
封装的好处:
- 对象代表什么,就得封装对应的数据,并提供数据对应的行为。
- 降低我们的学习成本,可以少学、少记,或者说压根不用学,不用记对象有哪些方法,有需要时去找就行。
sun公司为了简化我们的开发,提供了很多很多的对象给我们,每个对象又有很多很多的方法。
3.2 private关键字
- private是一个修饰符
- 可以用来修饰成员(成员变量、成员方法)
- 被 private 修饰的成员,只能在本类进行访问
针对private修饰的成员变量,如果需要被其他类使用,提供相应的操作
- 提供“ set变量名(参数) ”方法,用于设置成员变量的值,方法用public修饰
- 提供“ get变量名() ”方法,用于获取成员变量的值,方法用public修饰
🌰示例代码:
/*
学生类
*/
class Student {
//成员变量
String name;
private int age;
//提供get/set方法
public void setAge(int a) {
if(a<0 || a>120) {
System.out.println("你给的年龄有误");
} else {
age = a;
}
}
public int getAge() {
return age;
}
//成员方法
public void show() {
System.out.println(name + "," + age);
}
}
/*
学生测试类
*/
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s = new Student();
//给成员变量赋值
s.name = "林青霞";
s.setAge(30);
//调用show方法
s.show();
}
}
4、就近原则和this关键字
就近原则:谁离我近,我就用谁。
- this修饰的变量用于指代成员变量,其主要作用是:区分 局部变量 和 成员变量 的重名问题
- 方法的形参如果与成员变量 同名,不带this修饰的变量指的是形参,而不是成员变量
- 方法的形参 没有 与成员变量同名,不带this修饰的变量指的是成员变量
public class Student {
private String name;
private int 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;
}
public void show() {
System.out.println(name + "," + age);
}
}
🌰示例代码:
public class GirlFriend{
// 属性
private int age; // 0
public void method(){
int age = 10
System.out.println(age); // 10
System.out.println(this.age); // 0
}
}
public class Student {
private String name;
private int 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;
}
public void show() {
System.out.println(name + "," + age);
}
}
5、构造方法
5.1 构造方法概述
构造方法也叫构造器、构造函数。
作用:在创建对象的时候给成员变量进行初始化(赋值)。
5.2 构造方法的格式
public class Student{
修饰符 类名(参数){
方法体;
}
}
特点:
- 方法名与类名相同,大小写也要一致
- 没有返回值类型,连 void 都没有
- 没有具体的返回值(不能由return带回结果数据)
执行时机:
- 创建对象的时候由虚拟机调用,不能手动调用构造方法
- 每创建一次对象,就会调用一次构造方法
5.3 构造方法的注意事项
① 构造方法的创建
- 如果没有定义构造方法,系统将给出一个默认的无参数构造方法
- 如果定义了构造方法,系统将不再提供默认的构造方法
如果定义了有参构造,系统就不在提供默认的无参构造,此时不写无参构造的话,会报错。
② 构造方法的重载
- 带参构造方法,和无参构造方法,两者方法名相同,但是参数不同,这叫做构造方法的重载。
③ 推荐的使用方式
- 无论是否使用,都手工书写无参数构造方法,和带带全部参数的构造方法
6、标准的javabean类
① 类名需要见名知意
② 成员变量使用 private 修饰
③ 提供至少两个构造方法
- 无参构造方法
- 带全部参数的构造方法
④ 成员方法
- 提供每一个成员变量对应的 setXxx()/getXxx()
- 如果还有其他行为,也需要写上
🌰示例代码:
需求:定义标准学生类,要求分别使用空参和有参构造方法创建对象,空参创建的对象通过setXxx赋值,有参创建的对象直接赋值,并通过show方法展示数据。
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;
}
public void show() {
System.out.println(name + "," + age);
}
}
/*
创建对象并为其成员变量赋值的两种方式
1:无参构造方法创建对象后使用setXxx()赋值
2:使用带参构造方法直接创建带有属性值的对象
*/
public class StudentDemo {
public static void main(String[] args) {
//无参构造方法创建对象后使用setXxx()赋值
Student s1 = new Student();
s1.setName("林青霞");
s1.setAge(30);
s1.show();
//使用带参构造方法直接创建带有属性值的对象
Student s2 = new Student("林青霞",30);
s2.show();
}
}
⭐️快捷键:
- alt + insert
- alt + Fn + insert
插件PTG 1秒生成标准Javabean
📖练习:
public class User {
//1.私有化全部的成员变量
//2.空参构造
//3.带全部参数的构造
//4.针对于每一个私有化的成员变量都要提供其对应的get和set方法
//5.如果当前事物还有其他行为,那么也要写出来,比如学生的吃饭,睡觉等行为
private String username;//用户名
private String password;//密码
private String email;//邮箱
private char gender;//性别
private int age;//年龄
//空参构造方法
public User() {
}
//带全部参数的构造
public User(String username, String password, String email, char gender, int age) {
this.username = username;
this.password = password;
this.email = email;
this.gender = gender;
this.age = age;
}
//get和set
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void eat(){
System.out.println(username + "在吃饭");
}
}
public class Test {
public static void main(String[] args) {
//写一个标准的javabean类
//咱们在课后只要能把这个标准的javabean能自己写出来,那么就表示今天的知识点就ok了
//利用空参构造创建对象
User u1 = new User();
//如果利用空参创建对象,还想赋值只能用set方法赋值
u1.setUsername("zhangsan");
u1.setPassword("1234qwer");
u1.setEmail("itheima@itcast.cn");
u1.setGender('男');
u1.setAge(23);
//获取属性的值并打印
System.out.println(u1.getUsername() + ", " + u1.getPassword()
+ ", " + u1.getEmail() + ", " + u1.getGender() + ", " + u1.getAge());
u1.eat();
System.out.println("=============================");
//简单的办法
//利用带全部参数的构造来创建对象
//快捷键:ctrl + p
User u2 = new User("lisi","12345678","lisi@itcast.cn",'女',24);
System.out.println(u2.getUsername() + ", " + u2.getPassword()
+ ", " + u2.getEmail() + ", " + u2.getGender() + ", " + u2.getAge());
u2.eat();
}
}
7、三种情况的对象内存图
1、对象内存图
在java运行的时候,虚拟机JVM会占用计算机一部分内存空间,为了更好地利用内存,JVM把它分成了五个部分,每个部分都有自己各自的作用。
当我们要运行一个类的时候,这个类的字节码文件都会被加载到方法区当中 临时存储。
注意:
从JDK8开始,取消方法区,新增元空间。把原来方法区的多种功能进行拆分
有的功能放到了堆中,有的功能放到了元空间中。
而 加载字节码文件的功能 在 JDK8 以后就归属 元空间 了。
- 当运行一个类的时候,这个类的字节码文件就会加载到方法区当中 临时存储。
- 当方法被调用的时候,就要 进栈 执行,而方法里面的变量也在里面。当方法执行完之后它就要出栈。
- 只要是 new 出来的东西就会在堆里面开辟一个小空间,开辟出来的空间都会有它自己的地址值。
2、一个对象的内存图
首先我们要知道,当我们在创建一个对象的时候,内存里面至少会做7件事情。
Student s = new Student();
1.加载class文件
把Student这个类的字节码文件,加载到内存。
2.声明局部变量
对 = 左边的 s 进行声明。
3.在堆内存中开辟一个空间
说的就是 = 的右边,针对 new 关键字,在堆里面开辟一个小空间。这个小空间就是我们平时所说的对象。
4.默认初始化
5.显示初始化
6.构造方法初始化
4、5、6 三步其实都是对第3步中的 变量 来赋值。
7.将堆内存中的地址值赋值给左边的局部变量
🌰画图解释:
1:程序从main方法开始执行,把StudentTest这个类的字节码文件加载到方法区里面,这里面会把main方法临时存储,然后 虚拟机 会自动地调用程序的入口main方法。
2:main 方法会被加载到 栈 里面,然后就要开始执行main方法里面的代码了。
3:创建一个对象。创建对象 虚拟机 至少做了7个步骤。
①:先加载 class文件 ,在方法区里面会把Student.class加载到里面 临时存储,里面会有Student的所有信息(所有的成员变量、所有的成员方法)。
②:声明局部变量,就是 创建对象 = 左边的代码。在main方法中开辟一个空间,这个空间的名字就叫做 s ,这个空间能存储 Student 这个对象的地址值。
③:在堆内存中开辟一个空间,就是 创建对象 = 右边的代码。只要有 new 就是在堆里面开辟了一个小空间,而堆里面的空间都是有地址值的(假设地址值是001)。这个空间里面就会把Student类里面所有的 成员变量 拷贝一份放过来。除此之外,还会有所有 成员方法 的地址,以后用对象调用方法的时候就能找到对应的方法。
④:首先会进行默认初始化。(例子中一开始是 null 和 0)
⑤:再进行显示初始化。如果一开始定义成员变量的时候直接给值,默认初始化值 就会被 显示初始化值覆盖 。
String name = “张三”;
int age = 23;
⑥:构造方法初始化。(例子中调用的是空参构造,空参构造里面没有写代码,所以可以忽略)
⑦:将堆内存中的地址值赋值给左边的局部变量,(例子中就是把 001 通过 = 运算符赋值给了左边的变量 s ,此时 s 这个空间里面就会存储地址值 001 )。
4:直接打印 s ,就是打印变量 s 中记录的地址值(001
)。
5:通过 地址值 获取 成员变量(null、0
) 。
6、7:把 “阿强” 赋值给 001 的 name,把 “23” 赋值给 001 的 age。
8:(阿强、23
)
9:通过 001 空间,找成员方法的地址,然后在方法区里面找成员方法,接着 成员方法 就会被 加载进栈。
10:(好好学习
)
study执行完后出栈,main方法也执行完后出栈,main方法里面的 变量 自然 也没有了。当变量消失后,针对于堆内存中的对象来讲,就意味着没有用到这个对象(专业来说就是 没有变量指向这个空间),这个空间也会消失。
在这里插入图片描述
3、多个对象的内存图
🌰画图解释:
❓第二次创建对象,.class字节码文件是否要再加载一次?
📚答:不需要。
4、两个变量指向同一个对象内存图
🌰画图解释:
5、this的内存原理
this的作用:区分局部变量和成员变量
this的本质:所在方法调用者的地址值
🌰画图解释:
这里的this都是 所在方法调用者的地址值。
6、基本数据类型和引用数据类型的区别
从内存的角度去解释:
基本数据类型:数据值是存储在自己的空间中。
特点:赋值给其他变量,也是赋的真实的值。
引用数据类型:数据值是存储在其他空间中,自己空间中存储的是地址值。
特点:赋值给其他变量,赋的是地址值。
🌰画图解释:
7、局部变量和成员变量的区别
成员变量:类中方法外的变量
局部变量:方法中的变量
⭐️其他区别:
区别 | 成员变量 | 局部变量 |
---|---|---|
类中位置不同 | 类中,方法外 | 方法内、方法声明上 |
初始化值不同 | 有默认初始化值 | 没有,使用之前需要完成赋值 |
内存位置不同 | 堆内存 | 栈内存 |
生命周期不同 | 随着对象的创建而存在,随着对象的消失而消失 | 随着方法的调用而存在,随着方法的运行结束而消失 |
作用域 | 整个类中有效 | 当前方法中有效 |
面向对象综合训练
1、文字版格斗游戏
需求:
格斗游戏,每个游戏角色的姓名,血量,都不相同,在选定人物的时候(new对象的时候),这些信息就应该被确定下来。
举例:
程序运行之后结果为:
姓名为:乔峰 血量为:100
姓名为:鸠摩智 血量为:100
乔峰举起拳头打了鸠摩智一下,造成了XX点伤害,鸠摩智还剩下XXX点血。
鸠摩智举起拳头打了鸠摩智一下,造成了XX点伤害,乔峰还剩下XXX点血。
乔峰举起拳头打了鸠摩智一下,造成了XX点伤害,鸠摩智还剩下XXX点血。
鸠摩智举起拳头打了鸠摩智一下,造成了XX点伤害,乔峰还剩下XXX点血。
乔峰K.O.了鸠摩智
📖代码示例:
public class GameTest {
public static void main(String[] args) {
//1.创建第一个角色
Role r1 = new Role("乔峰",100);
//2.创建第二个角色
Role r2 = new Role("鸠摩智",100);
//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;
}
}
}
}
public class Role {
private String name;
private int blood;
public Role() {
}
public Role(String name, int blood) {
this.name = name;
this.blood = blood;
}
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;
}
//定义一个方法用于攻击别人
//思考:谁攻击谁?
//Role r1 = new Role();
//Role r2 = new Role();
//r1.攻击(r2);
//方法的调用者去攻击参数
public void attack(Role role) {
//计算造成的伤害 1 ~ 20
Random r = new Random();
int hurt = r.nextInt(20) + 1;
//剩余血量
int remainBoold = role.getBlood() - hurt;
//对剩余血量做一个验证,如果为负数了,就修改为0
remainBoold = remainBoold < 0 ? 0 : remainBoold;
//修改一下挨揍的人的血量
role.setBlood(remainBoold);
//this表示方法的调用者
System.out.println(this.getName() + "举起拳头,打了" + role.getName() + "一下," +
"造成了" + hurt + "点伤害," + role.getName() + "还剩下了" + remainBoold + "点血");
}
}
🍊文字版格斗游戏进阶
在上一个的基础上,我想看到人物的性别和长相,打斗的时候我想看到武功招式。
举例:
程序运行之后结果为:
姓名为:乔峰 血量为:100 性别为:男 长相为:气宇轩昂
姓名为:鸠摩智 血量为:100 性别为:男 长相为:气宇轩昂
乔峰使出了一招【背心钉】,转到对方的身后,一掌向鸠摩智背心的灵台穴拍去。给鸠摩智造成一处瘀伤。
鸠摩智使出了一招【游空探爪】,飞起身形自半空中变掌为抓锁向乔峰。结果乔峰退了半步,毫发无损。
。。。。
乔峰K.O.了鸠摩智
分析:
长相是提前定义好的,提前放在一个数组当中,程序运行之后,从数组中随机获取。
//男生长相数组
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一声惨叫,像滩软泥般塌了下去"
其中输出语句跟以前不一样了,用的是System.out.printf();该输出语句支持%s占位符
public class Test {
public static void main(String[] args) {
//两部分参数:
//第一部分参数:要输出的内容%s(占位)
//第二部分参数:填充的数据
System.out.printf("你好啊%s","张三");//用张三填充第一个%s
System.out.println();//换行
System.out.printf("%s你好啊%s","张三","李四");//用张三填充第一个%s,李四填充第二个%s
}
}
📖最终代码示例:
package com.itheima.test2;
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;
}
//定义一个方法用于攻击别人
//思考:谁攻击谁?
//Role r1 = new Role();
//Role r2 = new Role();
//r1.攻击(r2);
//方法的调用者去攻击参数
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(20) + 1;
//剩余血量
int remainBoold = role.getBlood() - hurt;
//对剩余血量做一个验证,如果为负数了,就修改为0
remainBoold = remainBoold < 0 ? 0 : remainBoold;
//修改一下挨揍的人的血量
role.setBlood(remainBoold);
//受伤的描述
//血量> 90 0索引的描述
//80 ~ 90 1索引的描述
//70 ~ 80 2索引的描述
//60 ~ 70 3索引的描述
//40 ~ 60 4索引的描述
//20 ~ 40 5索引的描述
//10 ~ 20 6索引的描述
//小于10的 7索引的描述
if (remainBoold > 90) {
System.out.printf(injureds_desc[0], role.getName());
}else if(remainBoold > 80 && remainBoold <= 90){
System.out.printf(injureds_desc[1], role.getName());
}else if(remainBoold > 70 && remainBoold <= 80){
System.out.printf(injureds_desc[2], role.getName());
}else if(remainBoold > 60 && remainBoold <= 70){
System.out.printf(injureds_desc[3], role.getName());
}else if(remainBoold > 40 && remainBoold <= 60){
System.out.printf(injureds_desc[4], role.getName());
}else if(remainBoold > 20 && remainBoold <= 40){
System.out.printf(injureds_desc[5], role.getName());
}else if(remainBoold > 10 && remainBoold <= 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());
}
}
package com.itheima.test2;
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;
}
}
}
}
2、两个对象数组练习
🍊对象数组(商品)
需求:
定义数组存储3个商品对象。
商品的属性:商品的id,名字,价格,库存。
创建三个商品对象,并把商品对象存入到数组当中。
📖代码示例:
package com.itheima.test3;
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;
}
}
package com.itheima.test3;
public class GoodsTest {
public static void main(String[] args) {
//1.创建一个数组
Goods[] arr = new Goods[3];
//2.创建三个商品对象
Goods g1 = new Goods("001","华为P40",5999.0,100);
Goods g2 = new Goods("002","保温杯",227.0,50);
Goods g3 = new Goods("003","枸杞",12.7,70);
//3.把商品添加到数组中
arr[0] = g1;
arr[1] = g2;
arr[2] = g3;
//4.遍历
for (int i = 0; i < arr.length; i++) {
//i 索引 arr[i] 元素
Goods goods = arr[i];
System.out.println(goods.getId() + ", " + goods.getName() + ", " + goods.getPrice() + ", " + goods.getCount());
}
}
}
⭐️键盘录入说明:
public class Test {
public static void main(String[] args) {
//键盘录入:
//第一套体系:
//nextInt(); 接收整数
//nextDouble();接收小数
//next();接收字符串
//遇到空格,制表符,回车就停止接受。这些符号后面的数据就不会接受了
//第二套体系:
//nextLine();接收字符串
//可以接收空格,制表符,遇到回车才停止接受数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int num1 = sc.nextInt(); // 123 123
System.out.println(num1);//123
System.out.println("请输入第二个整数");
int num2 = sc.nextInt();//不用键盘录入
System.out.println(num2);//123
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String str1 = sc.next();//abc bcd
System.out.println(str1);//abc
System.out.println("请输入第二个字符串");
String str2 = sc.next();//不用键盘录入
System.out.println(str2);//bcd
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String line1 = sc.nextLine();//abc bcd
System.out.println(line1);//abc bcd
System.out.println("请输入第二个字符串");
String line2 = sc.nextLine();//123 789
System.out.println(line2);//123 789
}
}
public class Test2 {
public static void main(String[] args) {
//键盘录入的两套体系不能混用的
//弊端:先用nextInt,再用nextLine会导致下面的nextLine接受不到数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int num = sc.nextInt();//123 + 回车
System.out.println(num);//123
System.out.println("请输入一个字符串");
String line = sc.nextLine();
System.out.println(line);//
}
}
结果:
下面的nextLine接受不到数据
📚目前暂时先用第一套体系 进行录入数据,等以后学习完 类型转换 ,再用第二套体系。等学习完第二套后,不管遇到什么数据(带空格、带制表符),都可以接收进来了。
🍊对象数组(汽车)
需求:
定义数组存储3部汽车对象。
汽车的属性:品牌,价格,颜色。
创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组当中。
📖代码示例:
package com.itheima.test5;
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;
}
}
package com.itheima.test5;
import java.util.Scanner;
public class CarTest {
public static void main(String[] args) {
//1.创建一个数组用来存3个汽车对象
Car[] arr = new Car[3];
//2.创建汽车对象,数据来自于键盘录入
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;
}
//3.遍历数组
for (int i = 0; i < arr.length; i++) {
Car car = arr[i];
System.out.println(car.getBrand() + ", " + car.getPrice() + ", " + car.getColor());
}
}
}
3、对象数组练习-判断并统计
🍊对象数组(手机)
需求 :
定义数组存储3部手机对象。
手机的属性:品牌,价格,颜色。
要求,计算出三部手机的平均价格
📖代码示例:
package com.itheima.test6;
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;
}
}
package com.itheima.test6;
import java.math.BigDecimal;
public class PhoneTest {
public static void main(String[] args) {
//1.创建一个数组
Phone[] arr = new Phone[3];
//2.创建手机的对象
Phone p1 = new Phone("小米",1999,"白色");
Phone p2 = new Phone("华为",4999,"蓝色");
Phone p3 = new Phone("魅族",3999,"红色");
//3.把手机对象添加到数组当中
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
//4.获取三部手机的平均价格
int sum = 0;
for (int i = 0; i < arr.length; i++) {
//i 索引 arr[i] 元素(手机对象)
Phone phone = arr[i];
sum = sum + phone.getPrice();
}
//5.求平均值
//数据能不写死,尽量不写死
//int avg = sum / arr.length;
double avg2 = sum * 1.0 / arr.length;
System.out.println(avg2);//3665.6666666666665
}
}
🍊对象数组(女朋友)
需求:
定义数组存储4个女朋友的对象
女朋友的属性:姓名、年龄、性别、爱好
要求1:计算出四女朋友的平均年龄
要求2:统计年龄比平均值低的女朋友有几个?并把她们的所有信息打印出来。
📖代码示例:
package com.itheima.test7;
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;
}
}
package com.itheima.test7;
public class GirlFriendTest {
public static void main(String[] args) {
//1.定义数组存入女朋友的对象
GirlFriend[] arr = new GirlFriend[4];
//2.创建女朋友对象
GirlFriend gf1 = new GirlFriend("小诗诗",18,"萌妹子","吃零食");
GirlFriend gf2 = new GirlFriend("小丹丹",19,"萌妹子","玩游戏");
GirlFriend gf3 = new GirlFriend("小惠惠",20,"萌妹子","看书,学习");
GirlFriend gf4 = new GirlFriend("小莉莉",21,"憨妹子","睡觉");
//3.把对象添加到数组当中
arr[0] = gf1;
arr[1] = gf2;
arr[2] = gf3;
arr[3] = gf4;
//4.求和
int sum = 0;
for (int i = 0; i < arr.length; i++) {
//i 索引 arr[i] 元素(女朋友对象)
GirlFriend gf = arr[i];
//累加
sum = sum + gf.getAge();
}
//5.平均值
int avg = sum / arr.length;
//6.统计年龄比平均值低的有几个,打印他们的信息
int count = 0;
for (int i = 0; i < arr.length; i++) {
GirlFriend gf = arr[i];
if(gf.getAge() < avg){
count++;
System.out.println(gf.getName() + ", " + gf.getAge() + ", " + gf.getGender() + ", " + gf.getHobby());
}
}
System.out.println(count + "个");
}
}
4、复杂对象数组练习-添加和遍历
定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。
学生的属性:学号,姓名,年龄。
要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
要求2:添加完毕之后,遍历所有学生信息。
要求3:通过id删除学生信息。如果存在,则删除,如果不存在,则提示删除失败。
要求4:删除完毕之后,遍历所有学生信息。
要求5:查询数组id为“heima002”的学生,如果存在,则将他的年龄+1岁
📖代码示例:
package com.itheima.test8;
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;
}
}
public class Test {
public static void main(String[] args) {
/*定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。
学生的属性:学号,姓名,年龄。
要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
要求2:添加完毕之后,遍历所有学生信息。
*/
//1.创建一个数组用来存储学生对象
Student[] arr = new Student[3];
//2.创建学生对象并添加到数组当中
Student stu1 = new Student(1, "zhangsan", 23);
Student stu2 = new Student(2, "lisi", 24);
//3.把学生对象添加到数组当中
arr[0] = stu1;
arr[1] = stu2;
//要求1:再次添加一个学生对象,并在添加的时候进行学号的唯一性判断。
Student stu4 = new Student(1, "zhaoliu", 26);
//唯一性判断
//已存在 --- 不用添加
//不存在 --- 就可以把学生对象添加进数组
boolean flag = contains(arr, stu4.getId());
if(flag){
//已存在 --- 不用添加
System.out.println("当前id重复,请修改id后再进行添加");
}else{
//不存在 --- 就可以把学生对象添加进数组
//把stu4添加到数组当中
//1.数组已经存满 --- 只能创建一个新的数组,新数组的长度 = 老数组 + 1
//2.数组没有存满 --- 直接添加
int count = getCount(arr);
if(count == arr.length){
//已经存满
//创建一个新的数组,长度 = 老数组的长度 + 1
//然后把老数组的元素,拷贝到新数组当中
Student[] newArr = creatNewArr(arr);
//把stu4添加进去
newArr[count] = stu4;
//要求2:添加完毕之后,遍历所有学生信息。
printArr(newArr);
}else{
//没有存满
//[stu1,stu2,null]
//getCount获取到的是2,表示数组当中已经有了2个元素
//还有一层意思:如果下一次要添加数据,就是添加到2索引的位置
arr[count] = stu4;
//要求2:添加完毕之后,遍历所有学生信息。
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());
}
}
}
//创建一个新的数组,长度 = 老数组的长度 + 1
//然后把老数组的元素,拷贝到新数组当中
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;
}
//1.我要干嘛? 唯一性判断
//2.我干这件事情,需要什么才能完成? 数组 id
//3.调用处是否需要继续使用方法的结果? 必须返回
public static boolean contains(Student[] arr, int 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;
}
}
}
//当循环结束之后,还没有找到一样的,那么就表示数组中要查找的id是不存在的。
return false;
}
}
package com.itheima.test8;
public class Test3 {
public static void main(String[] args) {
/*定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。
学生的属性:学号,姓名,年龄。
要求3:通过id删除学生信息
如果存在,则删除,如果不存在,则提示删除失败。
要求4:删除完毕之后,遍历所有学生信息。
*/
//1.创建一个数组用来存储学生对象
Student[] arr = new Student[3];
//2.创建学生对象并添加到数组当中
Student stu1 = new Student(1, "zhangsan", 23);
Student stu2 = new Student(2, "lisi", 24);
Student stu3 = new Student(3, "wangwu", 25);
//3.把学生对象添加到数组当中
arr[0] = stu1;
arr[1] = stu2;
arr[2] = stu3;
/*要求3:通过id删除学生信息
如果存在,则删除,如果不存在,则提示删除失败。*/
//要找到id在数组中对应的索引
int index = getIndex(arr, 2);
if (index >= 0){
//如果存在,则删除
arr[index] = null;
//遍历数组
printArr(arr);
}else{
//如果不存在,则提示删除失败
System.out.println("当前id不存在,删除失败");
}
}
//1.我要干嘛? 找到id在数组中的索引
//2.我需要什么? 数组 id
//3.调用处是否需要继续使用方法的结果? 要
public static int getIndex(Student[] arr , int id){
for (int i = 0; i < arr.length; i++) {
//依次得到每一个学生对象
Student stu = arr[i];
//对stu进行一个非空判断
if(stu != null){
int sid = stu.getId();
if(sid == id){
return i;
}
}
}
//当循环结束之后,还没有找到就表示不存在
return -1;
}
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());
}
}
}
}
package com.itheima.test8;
public class Test4 {
public static void main(String[] args) {
/*定义一个长度为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。
学生的属性:学号,姓名,年龄。
要求5:查询数组id为“2”的学生,如果存在,则将他的年龄+1岁*/
//1.创建一个数组用来存储学生对象
Student[] arr = new Student[3];
//2.创建学生对象并添加到数组当中
Student stu1 = new Student(1, "zhangsan", 23);
Student stu2 = new Student(2, "lisi", 24);
Student stu3 = new Student(3, "wangwu", 25);
//3.把学生对象添加到数组当中
arr[0] = stu1;
arr[1] = stu2;
arr[2] = stu3;
//4.先要找到id为2的学生对于的索引
int index = getIndex(arr, 2);
//5.判断索引
if(index >= 0){
//存在, 则将他的年龄+1岁
Student stu = arr[index];
//把原来的年龄拿出来
int newAge = stu.getAge() + 1;
//把+1之后的年龄塞回去
stu.setAge(newAge);
//遍历数组
printArr(arr);
}else{
//不存在,则直接提示
System.out.println("当前id不存在,修改失败");
}
}
//1.我要干嘛? 找到id在数组中的索引
//2.我需要什么? 数组 id
//3.调用处是否需要继续使用方法的结果? 要
public static int getIndex(Student[] arr , int id){
for (int i = 0; i < arr.length; i++) {
//依次得到每一个学生对象
Student stu = arr[i];
//对stu进行一个非空判断
if(stu != null){
int sid = stu.getId();
if(sid == id){
return i;
}
}
}
//当循环结束之后,还没有找到就表示不存在
return -1;
}
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());
}
}
}
}