第七次实验课代码

添加C04~C07
This commit is contained in:
2025-10-29 00:52:52 +08:00
parent 1986bbbe3e
commit 1c869f816f
24 changed files with 761 additions and 3 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
.idea/MarsCodeWorkspaceAppSettings.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.codeverse.userSettings.MarscodeWorkspaceAppSettingsState">
<option name="progress" value="1.0" />
</component>
</project>

6
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

14
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/C02 Expresion/C02 Expresion.iml" filepath="$PROJECT_DIR$/C02 Expresion/C02 Expresion.iml" />
<module fileurl="file://$PROJECT_DIR$/C03 ControlFlow/C03 ControlFlow.iml" filepath="$PROJECT_DIR$/C03 ControlFlow/C03 ControlFlow.iml" />
<module fileurl="file://$PROJECT_DIR$/C04 ClassDefine/C04 ClassDefine.iml" filepath="$PROJECT_DIR$/C04 ClassDefine/C04 ClassDefine.iml" />
<module fileurl="file://$PROJECT_DIR$/C05 Extends/C05 Extends.iml" filepath="$PROJECT_DIR$/C05 Extends/C05 Extends.iml" />
<module fileurl="file://$PROJECT_DIR$/C06 Polymorphism/C06 Polymorphism.iml" filepath="$PROJECT_DIR$/C06 Polymorphism/C06 Polymorphism.iml" />
<module fileurl="file://$PROJECT_DIR$/C07 StaticAndEnum/C07 StaticAndEnum.iml" filepath="$PROJECT_DIR$/C07 StaticAndEnum/C07 StaticAndEnum.iml" />
<module fileurl="file://$PROJECT_DIR$/ClassOfJava.iml" filepath="$PROJECT_DIR$/ClassOfJava.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -13,7 +13,7 @@ public class EncryptDemo {
// for(char c:enc)
// System.out.print(c);
System.out.println(Arrays.toString(enc));
System.out.println("密文:"+Arrays.toString(enc));
char[] dec= new char[enc.length];
for(int i=0;i<str.length();i++)
@@ -21,6 +21,6 @@ public class EncryptDemo {
// for(char c:dec)
// System.out.print(c);
System.out.println(Arrays.toString(dec));
System.out.println("明文:"+Arrays.toString(dec));
}
}

View File

@@ -9,7 +9,6 @@ public class NumberCounter {
hash[(int)(num%10)]++;
num/=10;
}
for(int i : hash)
System.out.print(i+" ");
System.out.println();

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,68 @@
public class Hero {
String name;//名称
char sex;//性别
int cost;//费用
int health;//生命值
int magic;//魔法值
int attack;//攻击力
int level;//等级(1-3) 1
int physicalResist;//物理抗性
int magicResist;//魔法抗性
//升级行为方法
public void levelUp(){
if (level < 3) {
this.level++;
this.health = (int) (this.health * 1.5);
this.attack = (int) (this.attack * 1.5);
System.out.format("%s升级到%d级\n", this.name, this.level);
}
}
//攻击行为方法
public void attack(Hero target){
if(this.health>0) {
int damage = calculateDamage(attack, target.physicalResist);
System.out.format("%s攻击了%s造成了%d点伤害\n", name, target.name, attack);
//必须为有效伤害
if (damage > 0)
target.takeDamage(damage);
else
System.out.println("攻击失败");
}
else
System.out.println(name+"已死亡,攻击失败");
}
//受到伤害行为方法
public void takeDamage(int damage){
health -= damage;
health=Math.max(health,0);
if(health>0)
System.out.format("%s受到了%d点伤害剩余生命值%d\n",name,damage,health);
else
System.out.format("%s受到了%d点伤害剩余生命值为0已被击败\n",name,damage);
}
private int calculateDamage(int damage,int resist){
return (int)(damage*1.0/(1+resist*1.0/100));
}
//无参构造器
public Hero() {
this.level=1;
}
//有参构造器
public Hero(String name, char sex, int cost, int health, int magic, int attack, int physicalResist, int magicResist) {
this();//在有参构造器中调用无参构造器
this.name = name;
this.sex = sex;
this.cost = cost;
this.health = health;
this.magic = magic;
this.attack = attack;
this.physicalResist = physicalResist;
this.magicResist = magicResist;
}
}

View File

@@ -0,0 +1,38 @@
public class Test {
public static void main(String[] args) {
//1.无参构造器,逐一赋值
Hero almin = new Hero();
almin.name="almin";
almin.sex='m';
almin.cost=1;
almin.health=1000;
almin.magic=100;
almin.attack=60;
almin.physicalResist=50;
almin.magicResist=50;
System.out.println(almin.name);
System.out.println(almin.health);
System.out.println(almin.level);
//2.有参构造器
Hero alen = new Hero("alen",'m',1,600,100,60,100,50);
System.out.println(alen.name);
System.out.println(alen.health);
System.out.println(alen.level);
//3.攻击
//almin.attack(alen);
System.out.println("游戏开始");
alen.levelUp();
int round = 0;
while(almin.health>0 && alen.health>0){
round++;
System.out.println(""+round+"回合");
almin.attack(alen);
alen.attack(almin);
System.out.println("=====================");
}
System.out.format("%s获胜%s失败",almin.health==0?alen.name:almin.name,
almin.health==0?almin.name:alen.name);
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,35 @@
package shape;
import java.awt.*;
public class Circle extends Shape {
private int radius;
@Override
public double getArea(){
return Math.PI*radius*radius;
}
@Override
public double getPerimeter(){
return 2*Math.PI*radius;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
// 绘制圆形
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
// 绘制信息
g.setColor(Color.BLACK);
g.drawString(String.format("面积: %.2f", getArea()), x + radius + 5, y);
g.drawString(String.format("周长: %.2f", getPerimeter()), x + radius + 5, y + 15);
}
public Circle(){
this(Color.RED,100,100,50);
}
public Circle(Color color,int x,int y,int radius){
super(color,x,y);
this.radius=radius;
}
}

View File

@@ -0,0 +1,14 @@
package shape;
import java.awt.*;
public class Rectangle extends Shape {
private int width,height;
public Rectangle() {
super();
}
public Rectangle(Color color, int x, int y, int width, int height) {
super(color, x, y);
this.width = width;
this.height = height;
}
}

View File

@@ -0,0 +1,52 @@
package shape;
import java.awt.*;
public class Shape {
protected Color color;
protected int x,y;
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public double getArea(){
return x*y;
}
public void setX(int x){
this.x=x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y=y;
}
public int getY(){
return y;
}
public double getPerimeter(){
return x*y;
}
public void move(int dx,int dy){
x += dx;
y += dy;
}
public void draw(Graphics g){
g.setColor(color);
g.fillRect(x,y,1,1);
}
Shape(){}
Shape(Color color,int x,int y){
this.color=color;
this.x=x;
this.y=y;
}
}

View File

@@ -0,0 +1,55 @@
package test;
import javax.swing.*;
import java.awt.*;
import shape.Circle;
public class ShapeDrawerTest extends JFrame {
/*******请在下面添加**************/
// 【任务1】定义一个包含5个元素的圆形数组
Circle[] circles = new Circle[5];
/*******请在上面添加**************/
// 初始化图形
private void initShapes() {
/*******请在下面添加**************/
// 【任务2】采用无参构造添加一个红色坐标为(100,100)半径为50的圆形并加入对应数组
circles[0] = new Circle();
// 【任务3】采用有参构造添加一个黄色坐标为(150,300)半径为70的圆形并加入对应数组
circles[1] = new Circle(Color.YELLOW, 150, 300, 70);
circles[2] = new Circle();
circles[3] = new Circle();
circles[4] = new Circle();
/*******请在上面添加**************/
}
// 重写绘制方法
@Override
public void paint(Graphics g) {
super.paint(g);
/*******请在下面添加**************/
// 绘制所有图形
// 【任务4】采用增强型for循环绘制所有图形
for (Circle circle : circles) {
circle.draw(g);
}
/*******请在上面添加**************/
// 绘制标题
g.setColor(Color.BLACK);
g.drawString("Java继承图形绘制示例", 300, 30);
}
public ShapeDrawerTest() {
// 初始化窗口
setTitle("图形绘制程序");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建各种图形对象
initShapes();
}
public static void main(String[] args) {
new ShapeDrawerTest().setVisible(true);
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,49 @@
package shape;
import java.awt.*;
public class Circle extends Shape {
private int radius;
public void setRadius(int r) {
radius = r;
}
public int getRadius() {
return radius;
}
@Override
public double getArea(){
return Math.PI*radius*radius;
}
@Override
public double getPerimeter(){
return 2*Math.PI*radius;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
// 绘制圆形
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
// 绘制信息
g.setColor(Color.BLACK);
g.drawString(String.format("面积: %.2f", getArea()), x + radius + 5, y);
g.drawString(String.format("周长: %.2f", getPerimeter()), x + radius + 5, y + 15);
}
public void drawCenterMark(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(x-5,y,x+5,y);
g.drawLine(x,y-5,x,y+5);
g.drawString("O", x+5, y+5);
}
public Circle(){
super();
}
public Circle(Color color,int x,int y,int radius){
super(color,x,y);
this.radius=radius;
}
}

View File

@@ -0,0 +1,56 @@
package shape;
import java.awt.*;
public class Rectangle extends Shape {
private int width,height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
@Override
public double getArea() {
return width*height;
}
@Override
public double getPerimeter() {
return 2*(width+height);
}
@Override
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, width, height);
// 绘制信息
g.setColor(Color.BLACK);
g.drawString(String.format("面积: %.2f", getArea()), x + width + 5, y);
g.drawString(String.format("周长: %.2f", getPerimeter()), x + width + 5, y + 15);
}
public void drawDiagonals(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(x, y, x+width, y+height);
g.drawLine(x, y+height, x+width, y);
}
public Rectangle() {
super();
}
public Rectangle(Color color, int x, int y, int width, int height) {
super(color, x, y);
this.width = width;
this.height = height;
}
}

View File

@@ -0,0 +1,52 @@
package shape;
import java.awt.*;
public class Shape {
protected Color color;
protected int x,y;
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public double getArea(){
return x*y;
}
public void setX(int x){
this.x=x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y=y;
}
public int getY(){
return y;
}
public double getPerimeter(){
return x*y;
}
public void move(int dx,int dy){
x += dx;
y += dy;
}
public void draw(Graphics g){
g.setColor(color);
g.fillRect(x,y,1,1);
}
Shape(){}
Shape(Color color,int x,int y){
this.color=color;
this.x=x;
this.y=y;
}
}

View File

@@ -0,0 +1,77 @@
package test;
import shape.Circle;
import shape.Rectangle;
import javax.swing.*;
import java.awt.*;
public class ShapeDrawerTest extends JFrame {
/*******请在下面添加**************/
// 【任务1】定义一个包含5个元素的圆形数组
Circle[] circles = new Circle[5];
Rectangle[] rectangles = new Rectangle[2];
private shape.Shape[] shapes = new shape.Shape[4];
/*******请在上面添加**************/
// 初始化图形
private void initShapes() {
/*******请在下面添加**************/
// 【任务2】采用无参构造添加一个红色坐标为(100,100)半径为50的圆形并加入对应数组
shapes[0] = new Circle();
((Circle)shapes[0]).setX(100);
((Circle)shapes[0]).setY(100);
((Circle)shapes[0]).setRadius(50);
((Circle)shapes[0]).setColor(Color.RED);
// 【任务3】采用有参构造添加一个黄色坐标为(150,300)半径为70的圆形并加入对应数组
shapes[1] = new Circle(Color.YELLOW, 150, 300, 70);
// 【任务4】采用无参构造添加一个绿色坐标为(250,80)宽为100高为80的矩形并加入对应数组
shapes[2] = new Rectangle();
((Rectangle)shapes[2]).setX(250);
((Rectangle)shapes[2]).setY(80);
((Rectangle)shapes[2]).setWidth(100);
((Rectangle)shapes[2]).setHeight(80);
((Rectangle)shapes[2]).setColor(Color.GREEN);
// 【任务5】采用有参构造添加一个粉色坐标为(300,300)宽为120高为60的矩形
shapes[3] = new Rectangle(Color.PINK, 300, 300, 120, 60);
// 【任务6】下移动第二个矩形50个单位
((Rectangle)shapes[3]).setY(this.getY()-50);
/*******请在上面添加**************/
}
// 重写绘制方法
@Override
public void paint(Graphics g) {
super.paint(g);
/*******请在下面添加**************/
// 绘制所有图形
// 【任务4】采用增强型for循环绘制所有图形
for (shape.Shape shape : shapes) {
shape.draw(g);
if (shape instanceof Circle) {
((Circle)shape).drawCenterMark(g);
}
if (shape instanceof Rectangle) {
((Rectangle)shape).drawDiagonals(g);
}
}
/*******请在上面添加**************/
// 绘制标题
g.setColor(Color.BLACK);
g.drawString("Java继承图形绘制示例", 300, 50);
}
public ShapeDrawerTest() {
// 初始化窗口
setTitle("图形绘制程序");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建各种图形对象
initShapes();
}
public static void main(String[] args) {
new ShapeDrawerTest().setVisible(true);
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,52 @@
import java.util.*;
/**
* 验证码工具类
*/
public class CaptchaUtils { // final修饰类不能被继承
// 【任务1】静态常量字符集全局固定
static final String CHAR_SET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 【任务2】静态常量验证码长度全局固定
static final int CAPTCHA_LENGTH=4;
// 【任务3】私有构造方法禁止创建实例工具类无需实例化
private CaptchaUtils(){
}
/**
* 【任务4】
* 静态方法generateCaptcha 生成随机验证码
* @return String 返回生成的随机验证码字符串
*/
public static String generateCaptcha(){
Random random = new Random();
//生成随机验证码
StringBuilder sb = new StringBuilder();
for(int i=0;i<CAPTCHA_LENGTH;i++){
//生成随机数索引
int index = random.nextInt(CHAR_SET.length());
//根据索引获取随机字符
sb.append(CHAR_SET.charAt(index));
}
return sb.toString();
}
/**
* 【任务5】
* 静态方法verifyCaptcha 验证验证码
* @param inputCaptcha 用户输入的验证码
* @param systemCaptcha 系统生成的验证码
* @return boolean 验证结果true表示验证通过false表示验证失败
*/
public static boolean verifyCaptcha(String inputCaptcha,String systemCaptcha){
return inputCaptcha.equalsIgnoreCase(systemCaptcha);
}
public static void main(String[] args) {
for(int i=0;i<10;i++)
System.out.println(generateCaptcha());
System.out.println(CaptchaUtils.verifyCaptcha(generateCaptcha(), generateCaptcha()));
}
}

View File

@@ -0,0 +1,72 @@
/**
* 登录状态枚举类
* 用final保证状态信息不可变用static提供工具方法
*/
public enum LoginStatus {
// 【任务3】枚举实例状态码和描述
// 成功登录
SUCCESS(200,"登录成功"),
// 密码错误
PASSWORD_ERROR(901,"密码错误"),
// 验证码错误
CAPTCHA_ERROR(902,"验证码错误"),
// 用户不存在
USER_NOT_FOUND(903,"用户不存在");
// 【任务1】定义 final修饰的属性确保状态信息不可修改
private final int code;
private final String msg;
/**
* 【任务2】
* 构造函数用于创建LoginStatus实例
* @param code 状态码
* @param msg 状态消息
*/
LoginStatus(int code, String msg) {
this.code = code;
this.msg = msg;
}
// 静态方法根据状态码获取枚举实例static工具方法
/**
* 【任务4】
* 静态方法: getByCode 根据状态码获取对应的登录状态枚举值
* @param code 状态码
* @return LoginStatus 对应的LoginStatus枚举值如果找不到匹配的状态码则返回null
*/
public static LoginStatus getByCode(int code){
for(LoginStatus status:values()){
if(status.code==code){
return status;
}
}
return null;
}
// getter方法final属性无需setter
/**
* 【任务5】
* 方法: getCode 获取code值
*
* @return int code值
*/
public int getCode() {
return code;
}
/**
* 任务【6】
* 方法: getMsg 获取消息内容
*
* @return String 返回当前对象的消息字符串
*/
public String getMsg() {
return msg;
}
}

View File

@@ -0,0 +1,55 @@
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
// 1. 生成验证码并展示
String systemCaptcha = CaptchaUtils.generateCaptcha(); // 调用静态方法
System.out.println("【登录】验证码:" + systemCaptcha);
// 2. 输入用户信息
System.out.print("请输入用户名:");
String username = scanner.nextLine();
System.out.print("请输入密码:");
String password = scanner.nextLine();
System.out.print("请输入验证码:");
String inputCaptcha = scanner.nextLine();
// 3. 验证登录(模拟业务逻辑)
LoginStatus status = checkLogin(username, password, inputCaptcha, systemCaptcha);
// 4. 【任务2】输出登录结果打印具体的登录结果和状态码
System.out.println("\n登录结果" + status.getMsg() + "(状态码:" + status.getCode() + "");
System.out.println("===================================\n");
}
}
/**
* 【任务1】
* 静态方法: checkLogin 模拟登录验证逻辑
* @param String username 用户名
* @param String password 密码
* @param String inputCaptcha 用户输入的验证码
* @param String systemCaptcha 系统生成的验证码
* @return LoginStatus 登录状态枚举,表示验证结果
*/
public static LoginStatus checkLogin(String username, String password, String inputCaptcha, String systemCaptcha) {
//admin 123456
// 1.校验验证码是否正确
if (!CaptchaUtils.verifyCaptcha(inputCaptcha, systemCaptcha)) {
return LoginStatus.CAPTCHA_ERROR;
}
// 2.校验用户名是否正确
if(!username.equals("admin")){
return LoginStatus.USER_NOT_FOUND;
}
// 3.校验密码是否正确
if(!password.equals("123456")){
return LoginStatus.PASSWORD_ERROR;
}
// 如果以上验证都通过,返回成功状态
return LoginStatus.SUCCESS;
}
}