当前位置: 首页 > 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.hskmm.com/?act=detail&tid=26694

相关文章:

  • 关于PPT的课后作业
  • RK 系列 GPU 驱动检查方法
  • 咕乡
  • Linux随记(十八) - 详解
  • week2课后作业
  • Java 语言程序设计(第二讲 方法)动手动脑与课后实验问题整理文档 - 20243867孙堃2405
  • 算法第一章
  • mac打开app提示文件损坏解决方案
  • QBXT2025S刷题 Day7题
  • 无需重新训练即可更新语音识别词汇
  • 深入解析:vscode中无法使用npm node
  • 第一次算法作业
  • AI元人文:新的评价与启示
  • Ai元人文:岐金兰回应
  • Why is English commonly used in scientific literature?
  • 第二次课程
  • 考研系列—操作系统:冲刺笔记(1-3章) - 指南
  • 智能照明系统厂家最新推荐榜:智慧光控与节能方案口碑之选
  • 2025工业网线优质厂家最新推荐榜:品质卓越与技术领先之选
  • 上海殡葬一条龙服务最新推荐:专业关怀与人性化服务口碑之选
  • 中空扳手实力厂家最新推荐榜:专业制造与耐用品质深度解析
  • 驾驭“人造太阳”:用 AI 来解锁聚变核能
  • sg.Multiline 和 sg.Output 有什么区别?怎么看起来一样?
  • 中科微GNSS卫星定位产品
  • 算法设计与分析第一章作业
  • Syncfusion重构Essential Studio套件,为开发者提供更灵活选择
  • vmware workstation17pro安装vmtools
  • 2025 年逸发粘接认证推荐:依托德系标准与全链条服务,打造粘接及复材技术解决方案优质选择
  • ZR 2025 十一集训 Day 8
  • Prj09--8088单板机C语言8253产生1KHz方波(1) - 详解