当前位置: 首页 > news >正文

java作业2

一:
代码:public class MethodOverload {
public static void main(String[] args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println("\nThe square of double 7.5 is " + square(7.5));
}

public static int square(int x) {return x * x;
}public static double square(double y) {return y * y;
}

}
核心:
1. 识别图片中的Java代码结构

2. 分析代码中的关键特性

3. 解释方法重载的概念和应用

4. 总结代码的特殊之处
结果:
The square of integer 7 is 49

The square of double 7.5 is 56.25
结论:
1. 方法重载:代码中定义了两个同名的 square 方法,但参数类型不同(一个接收 int 参数,另一个接收 double 参数)

2. 参数多态性:根据传入参数的类型,Java编译器会自动选择合适的方法版本执行

3. 代码复用:通过方法重载实现了相同功能(计算平方)的不同参数版本,提高了代码的灵活性和可读性

二:
import java.util.Random;

public class ArithmeticGenerator {
public static void main(String[] args) {
// 生成30道题目
for (int i = 0; i < 30; i++) {
String question = generateQuestion();
System.out.println((i + 1) + ". " + question);
}
}

/*** 生成一道四则运算题目* @return 题目字符串(如"12 + 5 =")*/
public static String generateQuestion() {Random random = new Random();int num1 = random.nextInt(20) + 1; // 1-20的随机整数int num2 = random.nextInt(20) + 1;String[] operators = {"+", "-", "×", "÷"};String operator = operators[random.nextInt(4)];// 处理减法(确保结果非负)if ("-".equals(operator)) {if (num1 < num2) {int temp = num1;num1 = num2;num2 = temp;}}// 处理除法(确保结果为整数)if ("÷".equals(operator)) {// 避免除以0while (num2 == 0 || num1 % num2 != 0) {num1 = random.nextInt(20) + 1;num2 = random.nextInt(20) + 1;}}// 构建题目字符串return num1 + " " + operator + " " + num2 + " =";
}

}

http://www.jsqmd.com/news/10100/

相关文章:

  • 关于PPT的课后作业
  • RK 系列 GPU 驱动检查方法
  • Day-15【选择与循环】选择结构-if语句 - 实践
  • 咕乡
  • opencv应用经典bug
  • Linux随记(十八) - 详解
  • 通信算法之281:大疆DJI无人机ID-DJI DroneID开源工程-相关问题-协议信息问题 - 实践
  • Linux 文件 MD5 校验完全指南
  • week2课后作业
  • Java 语言程序设计(第二讲 方法)动手动脑与课后实验问题整理文档 - 20243867孙堃2405
  • 算法第一章
  • 课后作业1
  • mac打开app提示文件损坏解决方案
  • 深入解析:RDMA简介3之四种子协议对比
  • QBXT2025S刷题 Day7题
  • 大语言模型中的注意力机制详解 - 教程
  • 无需重新训练即可更新语音识别词汇
  • 深入解析:vscode中无法使用npm node
  • 第一次算法作业
  • AI元人文:新的评价与启示
  • Why is English commonly used in scientific literature?
  • 第二次课程
  • 详细介绍:《云原生安全攻防》-- K8s网络策略:通过NetworkPolicy实现微隔离
  • 考研系列—操作系统:冲刺笔记(1-3章) - 指南
  • 【Axure高保真原型】交通事故大屏可视化分析案例 - 指南
  • 2025工业网线优质厂家最新推荐榜:品质卓越与技术领先之选
  • 上海殡葬一条龙服务最新推荐:专业关怀与人性化服务口碑之选
  • 中空扳手实力厂家最新推荐榜:专业制造与耐用品质深度解析
  • 驾驭“人造太阳”:用 AI 来解锁聚变核能
  • Flask中关于app.url_map属性的用法 - 详解