commit 0becd148306e9b95ce58925b0edae71e5541fc76 Author: Launchcore Date: Thu Nov 6 10:29:13 2025 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b618d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,204 @@ +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### MicrosoftOffice ### +*.tmp + +# Word temporary +~$*.doc* + +# Word Auto Backup File +Backup of *.doc* + +# Excel temporary +~$*.xls* + +# Excel Backup File +*.xlk + +# PowerPoint temporary +~$*.ppt* + +# Visio autosave temporary files +*.~vsd* + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk \ No newline at end of file diff --git a/BankSystem/.github/copilot-instructions.md b/BankSystem/.github/copilot-instructions.md new file mode 100644 index 0000000..e7b3c60 --- /dev/null +++ b/BankSystem/.github/copilot-instructions.md @@ -0,0 +1,127 @@ +# 角色设定 + +你是一位经验丰富的软件开发专家与编码助手,精通所有主流编程语言与框架。你的用户是一名独立开发者,正在进行个人或自由职业项目开发。你的职责是协助生成高质量代码、优化性能、并主动发现和解决技术问题。 + +--- + +# 核心目标 + +高效协助用户开发代码,并在无需反复提示的前提下主动解决问题。关注以下核心任务: + +- 编写代码 +- 优化代码 +- 调试与问题解决 + +确保所有解决方案都清晰易懂,逻辑严密。 + +--- + +## 阶段一:初始评估 + +1. 用户发出请求时,优先检查项目中的 `README.md` 文档以理解整体架构与目标。 +2. 若无文档,主动创建一份 `README.md`,包括功能说明、使用方式和核心参数。 +3. 利用已有上下文(文件、代码)充分理解需求,避免偏差。 + +--- + +## 阶段二:代码实现 + +### 1. 明确需求 +- 主动确认需求是否清晰,若有疑问,应立即询问。 +- 推荐最简单有效的方案,避免不必要的复杂设计。 + +### 2. 编写代码 +- 阅读现有代码,明确实现步骤。 +- 选择合适语言与框架,并遵循最佳实践(如 SOLID 原则)。 +- 编写简洁、可读、带注释的代码。 +- 优化可维护性与性能。 +- 按需提供单元测试。 +- 遵循语言标准编码规范(如 Python 使用 PEP 8)。 + +### 3. 调试与问题解决 +- 系统化分析问题,找出根因。 +- 明确说明问题来源及解决方式。 +- 在问题解决过程中持续与用户沟通,如需求变动能快速适应。 + +--- + +## 阶段三:完成与总结 + +1. 清晰总结本轮改动、完成目标与优化内容。 +2. 标注潜在风险或需留意的边界情况。 +3. 更新项目文档(如 `README.md`)以反映最新进展。 + +--- + +# 最佳实践 + +### Sequential Thinking(逐步思考工具) + +使用 [Sequential Thinking](https://github.com/smithery-ai/reference-servers/tree/main/src/sequentialthinking) 工具,以结构化的思维方式处理复杂、开放性问题。 + +- 将任务拆解为若干 **思维步骤(thought steps)**。 +- 每一步应包括: + 1.**明确当前目标或假设**(如:“分析登录方案”,“优化状态管理结构”)。 + 2.**调用合适的 MCP 工具**(如 `search_docs`、`code_generator`、`error_explainer`),用于执行查文档、生成代码或解释错误等操作。Sequential Thinking 本身不产出代码,而是协调过程。 + 3.**清晰记录本步骤的结果与输出**。 + 4.**确定下一步目标或是否分支**,并继续流程。 + +- 在面对不确定或模糊任务时: + - 使用“分支思考”探索多种方案。 + - 比较不同路径的优劣,必要时回滚或修改已完成的步骤。 + +- 每个步骤可带有如下结构化元数据: + -`thought`: 当前思考内容 + -`thoughtNumber`: 当前步骤编号 + -`totalThoughts`: 预估总步骤数 + -`nextThoughtNeeded`, `needsMoreThoughts`: 是否需要继续思考 + -`isRevision`, `revisesThought`: 是否为修订行为,及其修订对象 + -`branchFromThought`, `branchId`: 分支起点编号及标识 + +- 推荐在以下场景使用: + - 问题范围模糊或随需求变化 + - 需要不断迭代、修订、探索多解 + - 跨步骤上下文保持一致尤为重要 + - 需要过滤不相关或干扰性信息 + +--- + +### Context7(最新文档集成工具) + +使用 [Context7](https://github.com/upstash/context7) 工具获取特定版本的最新官方文档与代码示例,用于提升生成代码的准确性与当前性。 + +-**目的**:解决模型知识过时问题,避免生成已废弃或错误的 API 用法。 + +-**使用方式**: + 1.**调用方式**:在提示词中加入 `use context7` 触发文档检索。如果不确定部分用法时也建议自动使用。 + 2.**获取文档**:Context7 会拉取当前使用框架/库的相关文档片段。 + 3.**集成内容**:将获取的示例与说明合理集成到你的代码生成或分析中。 + +-**按需使用**:**仅在需要时调用 Context7**,例如遇到 API 模糊、版本差异大或用户请求查阅官方用法。避免不必要的调用,以节省 token 并提高响应效率。 + +-**集成方式**: + - 支持 Cursor、Claude Desktop、Windsurf 等 MCP 客户端。 + - 通过配置服务端集成 Context7,即可在上下文中获取最新参考资料。 + +-**优势**: + - 提升代码准确性,减少因知识过时造成的幻觉与报错。 + - 避免依赖训练时已过期的框架信息。 + - 提供明确、权威的技术参考材料。 + +--- + +# 沟通规范 + +- 除非用户要求以另一种语言回答,否则所有内容必须使用用户向你发出请求时使用的语言交流(包括代码注释)。 +- 遇到不清楚的内容应立即向用户提问。 +- 表达清晰、简洁、技术准确。 +- 在代码中应添加必要的注释解释关键逻辑。 +- 无论何时你想提问,总是调用 MCP mcp-feedback-enhanced(interactive_feedback命令)。 + +# MCP Interactive Feedback 规则 + +1. 在任何流程、任务、对话进行时,无论是询问、回复、或完成阶段性任务,皆必须调用 MCP mcp-feedback-enhanced。 +2. 每当收到用户反馈,若反馈内容非空,必须再次调用 MCP mcp-feedback-enhanced,并根据反馈内容调整行为。 +3. 仅当用户明确表示「结束」或「不再需要交互」时,才可停止调用 MCP mcp-feedback-enhanced,流程才算结束。 +4. 除非收到结束指令,否则所有步骤都必须重复调用 MCP mcp-feedback-enhanced。 +5. 完成任务前,必须使用 MCP mcp-feedback-enhanced 工具向用户询问反馈。 diff --git a/BankSystem/.gitignore b/BankSystem/.gitignore new file mode 100644 index 0000000..5ff6309 --- /dev/null +++ b/BankSystem/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/BankSystem/.idea/.gitignore b/BankSystem/.idea/.gitignore new file mode 100644 index 0000000..7d05e99 --- /dev/null +++ b/BankSystem/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# 依赖于环境的 Maven 主目录路径 +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/BankSystem/.idea/encodings.xml b/BankSystem/.idea/encodings.xml new file mode 100644 index 0000000..aa00ffa --- /dev/null +++ b/BankSystem/.idea/encodings.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/BankSystem/.idea/misc.xml b/BankSystem/.idea/misc.xml new file mode 100644 index 0000000..fdc35ea --- /dev/null +++ b/BankSystem/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/BankSystem/.idea/runConfigurations/BankSystem.xml b/BankSystem/.idea/runConfigurations/BankSystem.xml new file mode 100644 index 0000000..068940d --- /dev/null +++ b/BankSystem/.idea/runConfigurations/BankSystem.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/BankSystem/.idea/uiDesigner.xml b/BankSystem/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/BankSystem/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BankSystem/.idea/vcs.xml b/BankSystem/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/BankSystem/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/BankSystem/README.md b/BankSystem/README.md new file mode 100644 index 0000000..92bb456 --- /dev/null +++ b/BankSystem/README.md @@ -0,0 +1,76 @@ +# 简易银行管理系统 + +这是一个使用 Java Swing 构建的简单银行账户管理系统。 + +## 功能 + +* **账户管理**: + * 开户:创建一个新的银行账户,系统会自动生成唯一的账户ID。 + * 销户:删除一个现有账户。只有当账户余额为零时才能成功销户。 + * 查询:根据账户ID查询账户的详细信息,包括账户持有人姓名和当前余额。 +* **资金管理**: + * 存款:向指定账户存入金额。 + * 取款:从指定账户取出金额,账户余额必须充足。 + * 转账:在两个指定账户之间转移金额,源账户余额必须充足。 + +## 使用方式 + +1. 运行 `BankSystem.java` 文件启动应用程序。 +2. **开户**: + * 点击“开户”按钮。 + * 在弹出的对话框中输入账户持有人姓名。 + * 系统会提示账户创建成功,并显示新生成的账户ID。 +3. **查询账户**: + * 在“账户号”输入框中输入要查询的账户ID。 + * 点击“查询”按钮。 + * 如果账户存在,其姓名和余额将显示在相应的不可编辑字段中。 +4. **存款**: + * 首先查询一个账户或在“账户号”输入框中输入账户ID。 + * 点击“存款”按钮。 + * 在弹出的对话框中输入存款金额。 + * 操作成功后,账户余额会自动更新(如果当前查询的是该账户)。 +5. **取款**: + * 首先查询一个账户或在“账户号”输入框中输入账户ID。 + * 点击“取款”按钮。 + * 在弹出的对话框中输入取款金额。 + * 操作成功后,账户余额会自动更新(如果当前查询的是该账户)。 +6. **转账**: + * 首先查询源账户或在“账户号”输入框中输入源账户ID。 + * 点击“转账”按钮。 + * 在弹出的第一个对话框中输入目标账户ID。 + * 在弹出的第二个对话框中输入转账金额。 + * 操作成功后,源账户余额会自动更新(如果当前查询的是源账户)。 +7. **销户**: + * 首先查询一个账户或在“账户号”输入框中输入要销户的账户ID。 + * 点击“销户”按钮。 + * 系统会要求确认操作。 + * 只有当账户余额为零时,销户才能成功。成功后,界面上的账户信息字段将被清空。 + +## 数据存储 + +所有账户数据都存储在项目根目录下的 `accounts.json` 文件中。每个账户对象包含以下键: + +```json +[ + { + "accountId": "ACC16228383922", + "name": "张三", + "balance": 1000.50 + }, + { + "accountId": "ACC16228383950", + "name": "李四", + "balance": 500.00 + } +] +``` + +* `accountId`: (String) 唯一的账户标识符。 +* `name`: (String) 账户持有人的姓名。 +* `balance`: (double) 账户的当前余额。 + +## 技术栈 + +* Java +* Swing (用于GUI) +* Gson (用于JSON数据处理) diff --git a/BankSystem/accounts.json b/BankSystem/accounts.json new file mode 100644 index 0000000..acef977 --- /dev/null +++ b/BankSystem/accounts.json @@ -0,0 +1 @@ +[{"accountId":"ACC1749542730783","name":"lisi","balance":1.0},{"accountId":"ACC1749553162251","name":"zhangsan","balance":50.0},{"accountId":"ACC1749560275526","name":"张三","balance":10.0}] \ No newline at end of file diff --git a/BankSystem/pom.xml b/BankSystem/pom.xml new file mode 100644 index 0000000..15a5c9e --- /dev/null +++ b/BankSystem/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + me.momokko + BankSystem + 1.0-SNAPSHOT + + + 21 + 21 + UTF-8 + + + + + com.google.code.gson + gson + 2.13.1 + + + com.formdev + flatlaf + 3.6 + + + + \ No newline at end of file diff --git a/BankSystem/src/main/java/BankSystem.java b/BankSystem/src/main/java/BankSystem.java new file mode 100644 index 0000000..9218456 --- /dev/null +++ b/BankSystem/src/main/java/BankSystem.java @@ -0,0 +1,12 @@ +import com.formdev.flatlaf.FlatDarculaLaf; + +public class BankSystem { + public static void main(String[] args) { + FlatDarculaLaf.setup(); + javax.swing.SwingUtilities.invokeLater(() -> { + BankSystemUI ui = new BankSystemUI(); + ui.pack(); + ui.setVisible(true); + }); + } +} diff --git a/BankSystem/src/main/java/BankSystemCore.java b/BankSystem/src/main/java/BankSystemCore.java new file mode 100644 index 0000000..14877ef --- /dev/null +++ b/BankSystem/src/main/java/BankSystemCore.java @@ -0,0 +1,241 @@ +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class BankSystemCore { + private final Gson gson = new Gson(); + private static final String ACCOUNTS_FILE_PATH = "accounts.json"; + + private List loadAccounts() { + if (!Files.exists(Paths.get(ACCOUNTS_FILE_PATH))) { + return new ArrayList<>(); + } + try (FileReader reader = new FileReader(ACCOUNTS_FILE_PATH)) { + Type accountListType = new TypeToken>() {}.getType(); + List accounts = gson.fromJson(reader, accountListType); + return accounts == null ? new ArrayList<>() : accounts; + } catch (IOException e) { + e.printStackTrace(); + return new ArrayList<>(); + } + } + + private boolean saveAccounts(List accounts) { + try (FileWriter writer = new FileWriter(ACCOUNTS_FILE_PATH)) { + gson.toJson(accounts, writer); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + Account CreateAccount(String name) { + if (name == null || name.trim().isEmpty()) { + return null; + } + List accounts = loadAccounts(); + String accountId = "ACC" + System.currentTimeMillis(); + Account newAccount = new Account(accountId, name.trim(), 0.0); + accounts.add(newAccount); + if (saveAccounts(accounts)) { + return newAccount; + } else { + return null; + } + } + + Account QueryAccount(String accountId) throws AccountNotFoundException { + if (accountId == null || accountId.trim().isEmpty()) { + throw new AccountNotFoundException("账户ID不能为空。"); + } + List accounts = loadAccounts(); + Optional accountOpt = accounts.stream() + .filter(acc -> acc.getAccountId().equals(accountId.trim())) + .findFirst(); + if (accountOpt.isPresent()) { + return accountOpt.get(); + } else { + throw new AccountNotFoundException("账户 " + accountId + " 未找到。"); + } + } + + void DeleteAccount(String accountId) throws AccountNotFoundException, AccountOperationException { + if (accountId == null || accountId.trim().isEmpty()) { + throw new AccountNotFoundException("账户ID不能为空。"); + } + List accounts = loadAccounts(); + Optional accountOpt = accounts.stream() + .filter(acc -> acc.getAccountId().equals(accountId.trim())) + .findFirst(); + + if (accountOpt.isPresent()) { + Account accountToDelete = accountOpt.get(); + if (accountToDelete.getBalance() == 0.0) { + accounts.remove(accountToDelete); + if (!saveAccounts(accounts)) { + throw new AccountOperationException("删除账户 " + accountId + " 时保存失败。"); + } + } else { + throw new AccountOperationException("账户 " + accountId + " 余额不为零,无法删除。"); + } + } else { + throw new AccountNotFoundException("要删除的账户 " + accountId + " 未找到。"); + } + } + + void Deposit(String accountId, double amount) throws AccountNotFoundException, InvalidAmountException, AccountOperationException { + if (accountId == null || accountId.trim().isEmpty()) { + throw new AccountNotFoundException("账户ID不能为空。"); + } + if (amount <= 0) { + throw new InvalidAmountException("存款金额必须为正数。"); + } + List accounts = loadAccounts(); + Optional accountOpt = accounts.stream() + .filter(acc -> acc.getAccountId().equals(accountId.trim())) + .findFirst(); + + if (accountOpt.isPresent()) { + Account account = accountOpt.get(); + accounts.remove(account); + Account updatedAccount = new Account(account.getAccountId(), account.getName(), account.getBalance() + amount); + accounts.add(updatedAccount); + if (!saveAccounts(accounts)) { + throw new AccountOperationException("存款到账户 " + accountId + " 时保存失败。"); + } + } else { + throw new AccountNotFoundException("存款账户 " + accountId + " 未找到。"); + } + } + + void Withdraw(String accountId, double amount) throws AccountNotFoundException, InvalidAmountException, InsufficientBalanceException, AccountOperationException { + if (accountId == null || accountId.trim().isEmpty()) { + throw new AccountNotFoundException("账户ID不能为空。"); + } + if (amount <= 0) { + throw new InvalidAmountException("取款金额必须为正数。"); + } + List accounts = loadAccounts(); + Optional accountOpt = accounts.stream() + .filter(acc -> acc.getAccountId().equals(accountId.trim())) + .findFirst(); + + if (accountOpt.isPresent()) { + Account account = accountOpt.get(); + if (account.getBalance() >= amount) { + accounts.remove(account); + Account updatedAccount = new Account(account.getAccountId(), account.getName(), account.getBalance() - amount); + accounts.add(updatedAccount); + if (!saveAccounts(accounts)) { + throw new AccountOperationException("从账户 " + accountId + " 取款时保存失败。"); + } + } else { + throw new InsufficientBalanceException("账户 " + accountId + " 余额不足。当前余额: " + account.getBalance() + ", 取款金额: " + amount); + } + } else { + throw new AccountNotFoundException("取款账户 " + accountId + " 未找到。"); + } + } + + void Transfer(String fromAccountId, String toAccountId, double amount) throws AccountNotFoundException, InvalidAmountException, InsufficientBalanceException, AccountOperationException { + if (fromAccountId == null || fromAccountId.trim().isEmpty()) { + throw new AccountNotFoundException("源账户ID不能为空。"); + } + if (toAccountId == null || toAccountId.trim().isEmpty()) { + throw new AccountNotFoundException("目标账户ID不能为空。"); + } + if (fromAccountId.trim().equals(toAccountId.trim())) { + throw new AccountOperationException("源账户和目标账户不能相同。"); + } + if (amount <= 0) { + throw new InvalidAmountException("转账金额必须为正数。"); + } + + List accounts = loadAccounts(); + Account fromAccount = accounts.stream() + .filter(acc -> acc.getAccountId().equals(fromAccountId.trim())) + .findFirst() + .orElseThrow(() -> new AccountNotFoundException("源账户 " + fromAccountId + " 未找到。")); + + Account toAccount = accounts.stream() + .filter(acc -> acc.getAccountId().equals(toAccountId.trim())) + .findFirst() + .orElseThrow(() -> new AccountNotFoundException("目标账户 " + toAccountId + " 未找到。")); + + if (fromAccount.getBalance() >= amount) { + accounts.remove(fromAccount); + accounts.remove(toAccount); + + Account updatedFromAccount = new Account(fromAccount.getAccountId(), fromAccount.getName(), fromAccount.getBalance() - amount); + Account updatedToAccount = new Account(toAccount.getAccountId(), toAccount.getName(), toAccount.getBalance() + amount); + + accounts.add(updatedFromAccount); + accounts.add(updatedToAccount); + + if (!saveAccounts(accounts)) { + throw new AccountOperationException("转账时保存账户信息失败。"); + } + } else { + throw new InsufficientBalanceException("源账户 " + fromAccountId + " 余额不足。当前余额: " + fromAccount.getBalance() + ", 转账金额: " + amount); + } + } +} + +// Custom Exception Classes +class AccountNotFoundException extends Exception { + public AccountNotFoundException(String message) { + super(message); + } +} + +class InsufficientBalanceException extends Exception { + public InsufficientBalanceException(String message) { + super(message); + } +} + +class InvalidAmountException extends Exception { + public InvalidAmountException(String message) { + super(message); + } +} + +class AccountOperationException extends Exception { + public AccountOperationException(String message) { + super(message); + } +} + +class Account { + private String accountId; + private String name; + private double balance; + + public Account(String accountId, String name, double balance) { + this.accountId = accountId; + this.name = name; + this.balance = balance; + } + + public String getAccountId() { + return accountId; + } + + public String getName() { + return name; + } + + public double getBalance() { + return balance; + } +} \ No newline at end of file diff --git a/BankSystem/src/main/java/BankSystemUI.form b/BankSystem/src/main/java/BankSystemUI.form new file mode 100644 index 0000000..30049a7 --- /dev/null +++ b/BankSystem/src/main/java/BankSystemUI.form @@ -0,0 +1,128 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/BankSystem/src/main/java/BankSystemUI.java b/BankSystem/src/main/java/BankSystemUI.java new file mode 100644 index 0000000..dc9a75f --- /dev/null +++ b/BankSystem/src/main/java/BankSystemUI.java @@ -0,0 +1,142 @@ +import javax.swing.*; + +public class BankSystemUI extends JDialog { + private JTextField accountIdField; + private JButton QueryButton, CreateButton, DepositButton, WithdrawButton, TransferButton, DeleteButton; + private JTextField NameField, BalanceField; + private JPanel contentPane; + + private BankSystemCore core = new BankSystemCore(); + + public BankSystemUI() { + setResizable(false); + setContentPane(contentPane); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setTitle("简易银行系统"); + + QueryButton.addActionListener(e -> queryAccountAction()); + + CreateButton.addActionListener(e -> { + String name = JOptionPane.showInputDialog(this, "请输入账户名:", "创建账户", JOptionPane.PLAIN_MESSAGE); + if (name == null || name.trim().isEmpty()) { + if (name != null) { + JOptionPane.showMessageDialog(this, "账户名不能为空。", "创建账户错误", JOptionPane.ERROR_MESSAGE); + } + return; + } + try { + Account account = core.CreateAccount(name.trim()); + if (account != null) { + JOptionPane.showMessageDialog(this, "账户创建成功!\n账户ID: " + account.getAccountId(), "创建账户成功", JOptionPane.INFORMATION_MESSAGE); + accountIdField.setText(account.getAccountId()); + queryAccountAction(); + } else { + JOptionPane.showMessageDialog(this, "创建账户失败。", "创建账户错误", JOptionPane.ERROR_MESSAGE); + } + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, "创建账户时发生错误: " + ex.getMessage(), "创建账户错误", JOptionPane.ERROR_MESSAGE); + } + }); + + DepositButton.addActionListener(e -> { + String id = accountIdField.getText().trim(); + if (id.isEmpty()) { + JOptionPane.showMessageDialog(this, "请输入账户ID。", "存款错误", JOptionPane.ERROR_MESSAGE); + return; + } + String amt = JOptionPane.showInputDialog(this, "请输入存款金额:", "存款", JOptionPane.PLAIN_MESSAGE); + if (amt == null || amt.trim().isEmpty()) return; + try { + core.Deposit(id, Double.parseDouble(amt.trim())); + JOptionPane.showMessageDialog(this, "存款成功。", "存款成功", JOptionPane.INFORMATION_MESSAGE); + queryAccountAction(); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, "无效的金额格式。", "存款错误", JOptionPane.ERROR_MESSAGE); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "存款错误", JOptionPane.ERROR_MESSAGE); + } + }); + + WithdrawButton.addActionListener(e -> { + String id = accountIdField.getText().trim(); + if (id.isEmpty()) { + JOptionPane.showMessageDialog(this, "请输入账户ID。", "取款错误", JOptionPane.ERROR_MESSAGE); + return; + } + String amt = JOptionPane.showInputDialog(this, "请输入取款金额:", "取款", JOptionPane.PLAIN_MESSAGE); + if (amt == null || amt.trim().isEmpty()) return; + try { + core.Withdraw(id, Double.parseDouble(amt.trim())); + JOptionPane.showMessageDialog(this, "取款成功。", "取款成功", JOptionPane.INFORMATION_MESSAGE); + queryAccountAction(); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, "无效的金额格式。", "取款错误", JOptionPane.ERROR_MESSAGE); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "取款错误", JOptionPane.ERROR_MESSAGE); + } + }); + + TransferButton.addActionListener(e -> { + String from = accountIdField.getText().trim(); + if (from.isEmpty()) { + JOptionPane.showMessageDialog(this, "请输入源账户ID。", "转账错误", JOptionPane.ERROR_MESSAGE); + return; + } + String to = JOptionPane.showInputDialog(this, "请输入目标账户ID:", "转账", JOptionPane.PLAIN_MESSAGE); + if (to == null || to.trim().isEmpty()) return; + String amt = JOptionPane.showInputDialog(this, "请输入转账金额:", "转账", JOptionPane.PLAIN_MESSAGE); + if (amt == null || amt.trim().isEmpty()) return; + try { + core.Transfer(from, to.trim(), Double.parseDouble(amt.trim())); + JOptionPane.showMessageDialog(this, "转账成功。", "转账成功", JOptionPane.INFORMATION_MESSAGE); + queryAccountAction(); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, "无效的金额格式。", "转账错误", JOptionPane.ERROR_MESSAGE); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "转账错误", JOptionPane.ERROR_MESSAGE); + } + }); + + DeleteButton.addActionListener(e -> { + String id = accountIdField.getText().trim(); + if (id.isEmpty()) { + JOptionPane.showMessageDialog(this, "请输入要删除的账户ID。", "删除错误", JOptionPane.ERROR_MESSAGE); + return; + } + int res = JOptionPane.showConfirmDialog(this, "确认删除账户 " + id + "?", "删除确认", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); + if (res == JOptionPane.YES_OPTION) { + try { + core.DeleteAccount(id); + JOptionPane.showMessageDialog(this, "删除成功。", "删除成功", JOptionPane.INFORMATION_MESSAGE); + accountIdField.setText(""); + clearFields(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "删除错误", JOptionPane.ERROR_MESSAGE); + } + } + }); + } + + private void queryAccountAction() { + String id = accountIdField.getText().trim(); + if (id.isEmpty()) { + JOptionPane.showMessageDialog(this, "账户ID不能为空。", "查询错误", JOptionPane.ERROR_MESSAGE); + clearFields(); + return; + } + try { + Account acc = core.QueryAccount(id); + NameField.setText(acc.getName()); + BalanceField.setText(String.format("%.2f", acc.getBalance())); + } catch (Exception ex) { + JOptionPane.showMessageDialog(this, ex.getMessage(), "查询错误", JOptionPane.ERROR_MESSAGE); + clearFields(); + } + } + + private void clearFields() { + NameField.setText(""); + BalanceField.setText(""); + } + +} diff --git a/BankSystem/实验报告-实验8.docx b/BankSystem/实验报告-实验8.docx new file mode 100644 index 0000000..2cdfd4c Binary files /dev/null and b/BankSystem/实验报告-实验8.docx differ diff --git a/Example_src/Chapter1-10/.classpath b/Example_src/Chapter1-10/.classpath new file mode 100644 index 0000000..e34eb85 --- /dev/null +++ b/Example_src/Chapter1-10/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Example_src/Chapter1-10/.idea/.gitignore b/Example_src/Chapter1-10/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/Example_src/Chapter1-10/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/Example_src/Chapter1-10/.idea/encodings.xml b/Example_src/Chapter1-10/.idea/encodings.xml new file mode 100644 index 0000000..97626ba --- /dev/null +++ b/Example_src/Chapter1-10/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Example_src/Chapter1-10/.idea/misc.xml b/Example_src/Chapter1-10/.idea/misc.xml new file mode 100644 index 0000000..5af9c98 --- /dev/null +++ b/Example_src/Chapter1-10/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Example_src/Chapter1-10/.idea/modules.xml b/Example_src/Chapter1-10/.idea/modules.xml new file mode 100644 index 0000000..5f7e48f --- /dev/null +++ b/Example_src/Chapter1-10/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Example_src/Chapter1-10/.idea/vcs.xml b/Example_src/Chapter1-10/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/Example_src/Chapter1-10/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Example_src/Chapter1-10/.project b/Example_src/Chapter1-10/.project new file mode 100644 index 0000000..337a59d --- /dev/null +++ b/Example_src/Chapter1-10/.project @@ -0,0 +1,28 @@ + + + javaEE + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + + + 1741074534549 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/Example_src/Chapter1-10/.settings/org.eclipse.jdt.core.prefs b/Example_src/Chapter1-10/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3a21537 --- /dev/null +++ b/Example_src/Chapter1-10/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Example_src/Chapter1-10/bin/ch10/userinfo.sql b/Example_src/Chapter1-10/bin/ch10/userinfo.sql new file mode 100644 index 0000000..3e30322 --- /dev/null +++ b/Example_src/Chapter1-10/bin/ch10/userinfo.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS `userinfo`; +CREATE TABLE `userinfo` +( + `userId` int(11) NOT NULL auto_increment, + `loginname` varchar(20) default NULL, + `password` varchar(10) default NULL, + PRIMARY KEY (`userId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `userinfo` (`userId`, `loginname`, `password`) +VALUES (1, 'admin', 'admin'); \ No newline at end of file diff --git a/Example_src/Chapter1-10/javaEE.iml b/Example_src/Chapter1-10/javaEE.iml new file mode 100644 index 0000000..6f5bb1a --- /dev/null +++ b/Example_src/Chapter1-10/javaEE.iml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch01/HelloApplet.java b/Example_src/Chapter1-10/src/ch01/HelloApplet.java new file mode 100644 index 0000000..ead0369 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch01/HelloApplet.java @@ -0,0 +1,10 @@ +package ch01; + +import java.applet.Applet; +import java.awt.Graphics; + +public class HelloApplet extends Applet { + public void paint(Graphics g) { + g.drawString("这是一个最简单的Applet程序", 40, 50); + } +} diff --git a/Example_src/Chapter1-10/src/ch01/HelloWorld.java b/Example_src/Chapter1-10/src/ch01/HelloWorld.java new file mode 100644 index 0000000..d410b71 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch01/HelloWorld.java @@ -0,0 +1,14 @@ +package ch01; + +public class HelloWorld { + public static void main(String args[]) { + System.out.println("Hello World!"); + int a = 123, b; + b = a >>> 33; + System.out.println("b=" + b); + int[] AB = new int[]{6, 80, 2, 55, 451}; + System.out.println("AB[0]=" + AB[0]); + String[][] str1 = new String[][]{new String[3], new String[]{"hello"}}; + System.out.println("str1[0][0]=" + str1[0]); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/ArrayDemo.java b/Example_src/Chapter1-10/src/ch02/ArrayDemo.java new file mode 100644 index 0000000..c0e5f67 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/ArrayDemo.java @@ -0,0 +1,27 @@ +package ch02; + +public class ArrayDemo { + public static void main(String args[]) { + char[] AB; + AB = new char[3]; + AB[0] = 'a'; + AB[1] = 'b'; + AB[2] = 'c'; + System.out.println(AB[0]); + System.out.println(AB[1]); + System.out.println(AB[2]); + int[] AC = new int[2]; + AC[0] = 100; + AC[1] = 200; + System.out.println(AC[0]); + System.out.println(AC[1]); + int[] AD = {10, 20, 30, 40}; + System.out.println(AD[0]); + System.out.println(AD[1]); + System.out.println(AD[2]); + System.out.println(AD[3]); + System.out.println(AB.length); + System.out.println(AC.length); + System.out.println(AD.length); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/EscapeRout.java b/Example_src/Chapter1-10/src/ch02/EscapeRout.java new file mode 100644 index 0000000..1bdeb5a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/EscapeRout.java @@ -0,0 +1,9 @@ +package ch02; + +public class EscapeRout { + public static void main(String[] args) { + System.out.println("a\u0022.length() + \u0022b".length()); + System.out.println("a".length() + "b".length()); + System.out.println("a\".length()+\"b".length()); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/LeapYear.java b/Example_src/Chapter1-10/src/ch02/LeapYear.java new file mode 100644 index 0000000..5092b93 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/LeapYear.java @@ -0,0 +1,29 @@ +package ch02; + +public class LeapYear { + int year, month, day; + + void setdate(int y, int m, int d) //成员方法,设置日期值 + { //公有的,无返回值,有三个参数 + year = y; + month = m; + day = d; + } + + boolean isleapyear() //判断年份是否为闰年 + { //布尔型返回值,无参数 + return (year % 400 == 0) || (year % 100 != 0) && (year % 4 == 0); + } + + void print() //输出日期值,无返回值,无参数 + { + System.out.println("date is " + year + '-' + month + '-' + day); + } + + public static void main(String args[]) { + LeapYear a = new LeapYear(); //创建对象 + a.setdate(2012, 12, 25); //调用类方法 + a.print(); + System.out.println(a.year + " is a leap year? " + a.isleapyear()); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/Num2Rmb.java b/Example_src/Chapter1-10/src/ch02/Num2Rmb.java new file mode 100644 index 0000000..a620a4e --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/Num2Rmb.java @@ -0,0 +1,45 @@ +package ch02; + +import java.util.Arrays; + +public class Num2Rmb { + private String[] hanArr = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; + private String[] unitArr = {"拾", "佰", "仟"}; + + /*private String[] divide(double num)把一个浮点数分解成整数部分和小数部分字符串 + num 需要被分解的浮点数,return 分解出来的整数部分和小数部分。 + 第一个数组元素是整数部分,第二个数组元素是小数部分 */ + private String[] divide(double num) { + long zheng = (long) num; //将一个浮点数强制类型转换为long,即得到它的整数部分 + long xiao = Math.round((num - zheng) * 100);//浮点数减去整数部分乘以100再取整得到两位小数 +//下面用了两种方法把整数转换为字符串 + return new String[]{zheng + "", String.valueOf(xiao)}; + } + + /*private String toHanStr(String numStr)把一个四位的数字字符串变成汉字字符串 + numStr 需要被转换的四位的数字字符串,return 四位的数字字符串被转换成的汉字字符串 */ + private String toHanStr(String numStr) { + String result = ""; + int numLen = numStr.length(); + for (int i = 0; i < numLen; i++)//依次遍历数字字符串的每一位数字 + { + int num = numStr.charAt(i) - 48;//把char型数字转换成的int型数字,因为它们的ASCII码值恰好相差48 + if (i != numLen - 1 && num != 0) //如果不是最后一位数字且数字不是零,则需要添加单位(仟、佰、拾) + { + result += hanArr[num] + unitArr[numLen - 2 - i]; + } else //否则不要添加单位 + { + result += hanArr[num]; + } + } + return result; + } + + public static void main(String[] args) { + Num2Rmb nr = new Num2Rmb(); + System.out.println(Arrays.toString(nr.divide(326811125.45)));//测试把一个浮点数分解成整数部分和小数部分 + System.out.println(nr.toHanStr("8906"));//测试把一个四位的数字字符串变成汉字字符串 + } +} + + diff --git a/Example_src/Chapter1-10/src/ch02/SymmetryArray.java b/Example_src/Chapter1-10/src/ch02/SymmetryArray.java new file mode 100644 index 0000000..e3d2fb3 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/SymmetryArray.java @@ -0,0 +1,20 @@ +package ch02; + +public class SymmetryArray { + public static void main(String[] args) { + int[] n = {1, 2, 0, 2, 1}; + boolean flag = true; //假设对称 + for (int i = 0; i < n.length / 2; i++) { //循环数组长度的一半次 + if (n[i] != n[n.length - i - 1]) //比较元素 + { + flag = false; //不对称 + break; //结束循环 + } + } + if (flag) { + System.out.println("对称"); + } else { + System.out.println("不对称"); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch02/TestArrays.java b/Example_src/Chapter1-10/src/ch02/TestArrays.java new file mode 100644 index 0000000..287d4ff --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/TestArrays.java @@ -0,0 +1,18 @@ +package ch02; + +import java.util.Arrays; + +public class TestArrays { + public static void main(String[] args) { + int[] a = new int[]{3, 4, 5, 6}; // 定义一个a数组 + int[] a2 = new int[]{3, 4, 5, 6}; // 定义一个a2数组 + System.out.println("a数组和a2数组是否相等:" + Arrays.equals(a, a2)); // 将输出true + int[] b = Arrays.copyOf(a, 6); // 通过复制a数组,生成一个新的b数组 + System.out.println("a数组和b数组是否相等:" + Arrays.equals(a, b)); + System.out.println("b数组的元素为:" + Arrays.toString(b)); // 输出b数组的元素 + Arrays.fill(b, 2, 4, 1); // 将b数组的第2个元素(包含)到第4个元素(不包含)赋值为1 + System.out.println("b数组的元素为:" + Arrays.toString(b)); // 输出b数组的元素 + Arrays.sort(b); // 对b数组进行排序 + System.out.println("b数组的元素为:" + Arrays.toString(b)); // 输出b数组的元素 + } +} diff --git a/Example_src/Chapter1-10/src/ch02/TestLoan.java b/Example_src/Chapter1-10/src/ch02/TestLoan.java new file mode 100644 index 0000000..4f7f456 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/TestLoan.java @@ -0,0 +1,13 @@ +package ch02; + +public class TestLoan { + public static void main(String args[]) { + double dbp = 300000; + double dbi = 0.0459 / 12; + int nt = 30 * 12; + double dbpow = 1; + for (int i = 0; i < nt; i++) dbpow = dbpow * (1 + dbi); + double dbr = dbp * dbi * dbpow / (dbpow - 1); + System.out.println("你每月需还贷款R=" + dbr + "元/月"); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/TestTwoDimension.java b/Example_src/Chapter1-10/src/ch02/TestTwoDimension.java new file mode 100644 index 0000000..d5519f5 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/TestTwoDimension.java @@ -0,0 +1,18 @@ +package ch02; + +public class TestTwoDimension { + public static void main(String[] args) { + int[][] a; //定义一个二维数组 + a = new int[3][]; //初始化a是一个长度为3的数组,a数组的数组元素又是引用类型 + for (int i = 0; i < a.length; i++) //把a数组当成一维数组,遍历a数组的每个数组元素 + { + System.out.println(a[i]); + } + a[0] = new int[2]; //初始化a数组的第一个元素 + a[0][1] = 6; //访问a数组的第一个元素所指数组的第二个元素 + for (int i = 0; i < a[0].length; i++) //a数组的第一个元素是一个一维数组,遍历这个一维数组 + { + System.out.println(a[0][i]); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch02/TestparseInt.java b/Example_src/Chapter1-10/src/ch02/TestparseInt.java new file mode 100644 index 0000000..3eceba4 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/TestparseInt.java @@ -0,0 +1,12 @@ +package ch02; + +public class TestparseInt { + public static void main(String args[]) { + String str1 = "100"; + String str2 = "12345678"; + int int1 = Integer.parseInt(str1, 16); + long lng = Long.valueOf(str2).intValue(); + System.out.println(int1); + System.out.println(lng); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/Testvalue.java b/Example_src/Chapter1-10/src/ch02/Testvalue.java new file mode 100644 index 0000000..4a7105b --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/Testvalue.java @@ -0,0 +1,12 @@ +package ch02; + +public class Testvalue { + public static void main(String args[]) { + long lng = 12345678; + int int1 = 100; + String str1 = String.valueOf(lng); + String str2 = Integer.toString(int1, 16).toUpperCase(); + System.out.println(str1); + System.out.println(str2); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/TwoDementionArray.java b/Example_src/Chapter1-10/src/ch02/TwoDementionArray.java new file mode 100644 index 0000000..400f2ef --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/TwoDementionArray.java @@ -0,0 +1,15 @@ +package ch02; + +public class TwoDementionArray { + public static void main(String args[]) { + float a[][]; + a = new float[3][4]; + a[0][0] = 100.0f; + a[0][1] = 100.1f; + a[2][1] = 102.1f; + System.out.println(a[0][0]); + System.out.println(a[0][1]); + System.out.println(a[2][1]); + System.out.println(a[2][3]); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/UseArray.java b/Example_src/Chapter1-10/src/ch02/UseArray.java new file mode 100644 index 0000000..c7bf909 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/UseArray.java @@ -0,0 +1,29 @@ +package ch02; + +public class UseArray { + public static void main(String[] args) { + int[] s1 = {5, 6, 8, 21}; + int[] s2 = new int[s1.length]; //s2必须先初始化分配空间 + int[] s3; + int[] s4 = new int[s1.length]; //s4必须先初始化分配空间 + prnt(s1); + System.out.println("s2 use for cycled method"); + for (int i = 0; i < s1.length; i++) { //使用for循环复制数组 + s2[i] = s1[i]; + } + prnt(s2); + System.out.println("s3 use clone method"); + s3 = (int[]) s1.clone();//使用clone创建sorces副本,注意clone要使用强制转换 + prnt(s3); + System.out.println("s4 use arraycopy method"); + System.arraycopy(s1, 0, s4, 0, s1.length); + prnt(s4); + } + + public static void prnt(int[] a) { + for (int i = 0; i < a.length; i++) { + System.out.print(a[i] + " "); + } + System.out.println(); + } +} diff --git a/Example_src/Chapter1-10/src/ch02/Variable.java b/Example_src/Chapter1-10/src/ch02/Variable.java new file mode 100644 index 0000000..b94273c --- /dev/null +++ b/Example_src/Chapter1-10/src/ch02/Variable.java @@ -0,0 +1,19 @@ +package ch02; + +public class Variable { + public static void main(String[] args) { + char c = 'A'; + int i = 1; + double d = 2.5; + boolean b = true; + final double SALES_TAX_RATE = 7.5; + String s = "Hello Again"; + System.out.println("c =" + c); + System.out.println("i =" + i); + System.out.println("c =" + d); + System.out.println("b =" + b); + System.out.println("SALES TAX RATE =" + SALES_TAX_RATE); + System.out.println("s =" + s); + System.out.println("length of s =" + s.length()); + } +} diff --git a/Example_src/Chapter1-10/src/ch03/Average.java b/Example_src/Chapter1-10/src/ch03/Average.java new file mode 100644 index 0000000..949ec2f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/Average.java @@ -0,0 +1,12 @@ +package ch03; + +public class Average { + public static void main(String[] args) { + double n, sum = 0.0; + for (int i = 0; i < args.length; i++) { + sum = sum + Double.valueOf(args[i]).doubleValue(); + } + n = sum / args.length; + System.out.println("平均数:" + n); + } +} diff --git a/Example_src/Chapter1-10/src/ch03/BreakLoop.java b/Example_src/Chapter1-10/src/ch03/BreakLoop.java new file mode 100644 index 0000000..7e9f634 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/BreakLoop.java @@ -0,0 +1,14 @@ +package ch03; + +public class BreakLoop { + public static void main(String args[]) { + int i, j; + for (i = 0; i < 6; i++) { + for (j = 0; j < 100; j++) { + if (j == 5) break; + System.out.print("*"); + } + System.out.println(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch03/BuyChicken.java b/Example_src/Chapter1-10/src/ch03/BuyChicken.java new file mode 100644 index 0000000..0530b78 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/BuyChicken.java @@ -0,0 +1,18 @@ +package ch03; + +public class BuyChicken { + public static void main(String[] args) { + int I, J, K; + System.out.println(" 公鸡数I 母鸡数J 小鸡数K "); + for (I = 0; I <= 20; I++) // I 为公鸡数 + { + for (J = 0; J <= 33; J++) // J 为母鸡数 + { + K = 100 - I - J; // K 为小鸡数 + if (5 * I + 3 * J + K / 3.0 == 100) + System.out.println(" " + I + " " + J + " " + K); + } + } + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/ChangeLetter.java b/Example_src/Chapter1-10/src/ch03/ChangeLetter.java new file mode 100644 index 0000000..a15df1b --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/ChangeLetter.java @@ -0,0 +1,21 @@ +package ch03; + +import java.util.*; + +public class ChangeLetter { + public static void main(String args[]) { + String s = new String("abcABC123"); + System.out.println(s); + char a[] = s.toCharArray(); + for (int i = 0; i < a.length; i++) { + if (Character.isLowerCase(a[i])) { + a[i] = Character.toUpperCase(a[i]); + } else if (Character.isUpperCase(a[i])) { + a[i] = Character.toLowerCase(a[i]); + } + } + s = new String(a); + System.out.println(s); + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/Con_Break2.java b/Example_src/Chapter1-10/src/ch03/Con_Break2.java new file mode 100644 index 0000000..ae02871 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/Con_Break2.java @@ -0,0 +1,25 @@ +package ch03; + +class Con_Break2 { + public static void main(String args[]) { + int sum = 0, i, j; + for (i = 1; i <= 10; i++) //计算1+3+5+7+9. + { + if (i % 2 == 0) + continue; + sum = sum + i; + } + System.out.println("sum=" + sum); + for (j = 2; j <= 10; j++) //求10以内的素数 + { + for (i = 2; i <= j / 2; i++) { + if (j % i == 0) + break; + } + if (i > j / 2) { + System.out.println("" + j + "是素数"); + } + } + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/ForDemo.java b/Example_src/Chapter1-10/src/ch03/ForDemo.java new file mode 100644 index 0000000..5a974bb --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/ForDemo.java @@ -0,0 +1,12 @@ +package ch03; + +import java.util.*; + +public class ForDemo { + public static void main(String args[]) { + int a[] = {22, 2, 222, -1, -110, 0}; + Arrays.sort(a); + for (int i = 0; i <= 5; i++) System.out.println(a[i] + ","); + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/ForEachTest.java b/Example_src/Chapter1-10/src/ch03/ForEachTest.java new file mode 100644 index 0000000..3ee2e88 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/ForEachTest.java @@ -0,0 +1,10 @@ +package ch03; + +public class ForEachTest { + public static void main(String args[]) { + int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; + for (int a : arr) + System.out.println(a); + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/IfDemo.java b/Example_src/Chapter1-10/src/ch03/IfDemo.java new file mode 100644 index 0000000..61dec16 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/IfDemo.java @@ -0,0 +1,15 @@ +package ch03; + +public class IfDemo { + public static void main(String args[]) { + int c1 = 2; + int c2 = 3; + if (c1 == 1) { + System.out.println("c1=1"); + } else if (c2 <= 1) { + System.out.println("c2<=1"); + } else { + System.out.println("c1 != 1, c2>1"); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch03/NestFor.java b/Example_src/Chapter1-10/src/ch03/NestFor.java new file mode 100644 index 0000000..5b6f096 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/NestFor.java @@ -0,0 +1,13 @@ +package ch03; + +public class NestFor { + public static void main(String[] args) { + int i, j; + for (i = 0; i < 6; i++) { + for (j = 0; j <= i; j++) { + System.out.print("*"); + } + System.out.println(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch03/ReadKey.java b/Example_src/Chapter1-10/src/ch03/ReadKey.java new file mode 100644 index 0000000..39b2f50 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/ReadKey.java @@ -0,0 +1,19 @@ +package ch03; + +import java.util.Scanner; + +public class ReadKey { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int score = 0; + int sum = 0; + int count = -1; + System.out.println("输入分数(-1结束):"); + while (score != -1) { + count++; + sum += score; + score = scanner.nextInt(); + } + System.out.println("平均:" + (double) sum / count); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch03/SwitchDemo.java b/Example_src/Chapter1-10/src/ch03/SwitchDemo.java new file mode 100644 index 0000000..bc76876 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/SwitchDemo.java @@ -0,0 +1,21 @@ +package ch03; + +public class SwitchDemo { + public static void main(String args[]) { + int c = 2; + switch (c) { + case 1: + System.out.println("case 1 c=" + c); + break; + case 3: + System.out.println("case 3 c=" + c); + break; + case 5: + System.out.println("case 5 c=" + c); + break; + default: + System.out.println("default c=" + c); + } + } +} + diff --git a/Example_src/Chapter1-10/src/ch03/TestLoan.java b/Example_src/Chapter1-10/src/ch03/TestLoan.java new file mode 100644 index 0000000..06e65a1 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/TestLoan.java @@ -0,0 +1,13 @@ +package ch03; + +public class TestLoan { + public static void main(String args[]) { + double dbp = 300000; + double dbi = 0.0459 / 12; + int nt = 30 * 12; + double dbpow = 1; + for (int i = 0; i < nt; i++) dbpow = dbpow * (1 + dbi); + double dbr = dbp * dbi * dbpow / (dbpow - 1); + System.out.println("你每月需还贷款R=" + dbr + "元/月"); + } +} diff --git a/Example_src/Chapter1-10/src/ch03/WhileSum.java b/Example_src/Chapter1-10/src/ch03/WhileSum.java new file mode 100644 index 0000000..4a7f8df --- /dev/null +++ b/Example_src/Chapter1-10/src/ch03/WhileSum.java @@ -0,0 +1,14 @@ +package ch03; + +public class WhileSum { + public static void main(String args[]) { + double sum = 0, a = 1; + int i = 1; + while (i <= 20) { + a = a * (1.0 / i); + sum = sum + a; + i = i + 1; + } + System.out.println("sum=" + sum); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/BackAnimal.java b/Example_src/Chapter1-10/src/ch04/BackAnimal.java new file mode 100644 index 0000000..b9e6b80 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/BackAnimal.java @@ -0,0 +1,42 @@ +package ch04; + +abstract class Animal { + public abstract void eat(); //只有方法名,而没有方法体 +} + +class Dog extends Animal { + private String name; + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void eat() { + System.out.println("小狗啃骨头啦"); + } +} + +class Bird extends Animal { + public void fly() { + System.out.println("小鸟飞呀飞呀"); + } + + public void eat() { + System.out.println("小鸟吃虫子啦"); + } +} + +public class BackAnimal { + public static void main(String args[]) { + Animal an = new Dog(); + an.eat(); + an = new Bird(); + an.eat(); + } +} + + diff --git a/Example_src/Chapter1-10/src/ch04/BackwardObject.java b/Example_src/Chapter1-10/src/ch04/BackwardObject.java new file mode 100644 index 0000000..ecd9f96 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/BackwardObject.java @@ -0,0 +1,31 @@ +package ch04; + +class 类人猿 { + public 类人猿() { + System.out.println("类人猿 Created!"); + } + + void crySpeak() { + System.out.println(" 我是类人猿。"); + } +} + +class People1 extends 类人猿 { + public People1() { + System.out.println("People Created!"); + } + + void crySpeak() { + System.out.println(" 我是People。"); + } +} + +class BackwardObject { + public static void main(String[] args) { + 类人猿 originalPeople = new 类人猿(); + People1 people = new People1(); + originalPeople = people; + originalPeople.crySpeak(); + people.crySpeak(); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch04/CallHidenVar.java b/Example_src/Chapter1-10/src/ch04/CallHidenVar.java new file mode 100644 index 0000000..16fbe1b --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/CallHidenVar.java @@ -0,0 +1,41 @@ +package ch04; + +class Sum { + int n; + + float f() { + float sum = 0; + for (int i = 1; i <= n; i++) + sum = sum + i; + return sum; + } +} + +class Average extends Sum { + int n; + + float f() { + float c; + super.n = n; + c = super.f(); + return c / n; + } + + float g() { + float c; + c = super.f(); + return c / 2; + } +} + +public class CallHidenVar { + public static void main(String[] args) { + Average aver = new Average(); + aver.n = 100; + float result_1 = aver.f(); + float result_2 = aver.g(); + System.out.println("result_1=" + result_1); + System.out.println("result_2=" + result_2); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/CheckFact.java b/Example_src/Chapter1-10/src/ch04/CheckFact.java new file mode 100644 index 0000000..076553a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/CheckFact.java @@ -0,0 +1,19 @@ +package ch04; + +class Fact { + float fact(int n) { //定义计算n!的方法 + int i; + float x = 1; + for (i = 1; i < n; i++) + x = x * n; + return x; + } +} + +public class CheckFact { + public static void main(String[] args) { + Fact x = new Fact(); + System.out.println(x.fact(10)); //计算10! + System.out.println(x.fact(15)); //计算15! + } +} diff --git a/Example_src/Chapter1-10/src/ch04/CircleArea.java b/Example_src/Chapter1-10/src/ch04/CircleArea.java new file mode 100644 index 0000000..57dc50e --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/CircleArea.java @@ -0,0 +1,33 @@ +package ch04; + +import java.applet.*; +import java.awt.*; + +class Area { + float fun(float r) { + return 3.14159f * r * r; + } + + float get(float x, float y) { + return x + y; + } +} + +class Circle extends Area { + float fun(float r) { + return 3.14159f * 2.0f * r; + } +} + +public class CircleArea extends Applet { + Circle yuan; + + public void init() { + yuan = new Circle(); + } + + public void paint(Graphics g) { + g.drawString("调用子类重写的方法fun(): 园的面积= " + yuan.fun(5.0f), 5, 20); + g.drawString("调用继承父类的方法get(): x+y=" + yuan.get(12.0f, 8.0f), 5, 40); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Crctngle.java b/Example_src/Chapter1-10/src/ch04/Crctngle.java new file mode 100644 index 0000000..a62c6f2 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Crctngle.java @@ -0,0 +1,18 @@ +package ch04; + +import java.io.*; + +public class Crctngle { + public static void main(String[] args) { + Rectangle x1 = new Rectangle(); //声明类的对象并实例化 + Rectangle x2 = new Rectangle(50, 40); //声明类的对象并初始化 + Rectangle x3 = new Rectangle(x1); + System.out.println("x1.length()=" + x1.length()); + System.out.println("x1.width()=" + x1.width()); + System.out.println("x2.length()=" + x2.length()); + System.out.println("x2.width()=" + x2.width()); + System.out.println("x3.length()=" + x3.length()); + System.out.println("x3.width()=" + x3.width()); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/Demo.java b/Example_src/Chapter1-10/src/ch04/Demo.java new file mode 100644 index 0000000..2fcfc4a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Demo.java @@ -0,0 +1,19 @@ +package ch04; + +class ABC //friendly类 +{ + public int pub_i = 5; + + public void show() { + System.out.println("pub_i=" + pub_i); + } +} + +class Demo { + public static void main(String[] args) { + ABC abc = new ABC(); //使用本包中的friendly类 + System.out.println("abc.pub_i=" + abc.pub_i); + abc.pub_i = 10; + abc.show(); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Dispatch.java b/Example_src/Chapter1-10/src/ch04/Dispatch.java new file mode 100644 index 0000000..2ac41a7 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Dispatch.java @@ -0,0 +1,20 @@ +package ch04; + +class A { + void callme() { + System.out.println("Inside A's callme( ) method"); + } +} + +class B extends A { + void callme() { + System.out.println("Inside B's callme( ) method"); + } +} + +public class Dispatch { + public static void main(String args[]) { + A a = new B(); + a.callme(); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/DynamicState.java b/Example_src/Chapter1-10/src/ch04/DynamicState.java new file mode 100644 index 0000000..5675a42 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/DynamicState.java @@ -0,0 +1,31 @@ +package ch04; + +class 动物 { + void cry() { + } +} + +class 狗 extends 动物 { + void cry() { + System.out.println("狗cry():汪汪....."); + } +} + +class 猫 extends 动物 { + void cry() { + System.out.println("猫cry(): 喵喵....."); + } +} + +class DynamicState { + public static void main(String[] args) { + 动物 dongwu; + if (Math.random() >= 0.5) { + dongwu = new 狗(); //上转的对象 + dongwu.cry(); + } else { + dongwu = new 猫(); //上转的对象 + dongwu.cry(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Father.java b/Example_src/Chapter1-10/src/ch04/Father.java new file mode 100644 index 0000000..7da2449 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Father.java @@ -0,0 +1,11 @@ +package ch04; + +class Father { + void speak() { //无参数的speak()方法 + System.out.println("I am Father! "); + } + + void speak(String s) { //有参数的speak(String s)方法 + System.out.println("I like" + " " + s + ". "); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch04/Inheritance.java b/Example_src/Chapter1-10/src/ch04/Inheritance.java new file mode 100644 index 0000000..e834aa7 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Inheritance.java @@ -0,0 +1,37 @@ +package ch04; + +class superClass { + int x; + + superClass() { + x = 3; + System.out.println("in superClass : x = " + x); + } + + void doSomething() { + System.out.println("in superClass.doSomething( )"); + } +} + +class subClass extends superClass { + int x; + + subClass() { + super(); //call constructor of superClass + x = 5; + System.out.println("in subClass : x = " + x); + } + + void doSomething() { + super.doSomething(); //call method of superClass + System.out.println("in subClass.doSomething( )"); + System.out.println("super.x = " + super.x + " sub.x = " + x); + } +} + +public class Inheritance { + public static void main(String[] args) { + subClass subC = new subClass(); + subC.doSomething(); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/ItemsFibi.java b/Example_src/Chapter1-10/src/ch04/ItemsFibi.java new file mode 100644 index 0000000..caadea0 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/ItemsFibi.java @@ -0,0 +1,21 @@ +package ch04; + +class Fibi { + public long fibinacii(int n) { + long c = 0; + if (n == 1 || n == 2) + c = 1; + else + c = fibinacii(n - 1) + fibinacii(n - 2); + return c; + } +} + +public class ItemsFibi { + public static void main(String[] args) { + Fibi a = new Fibi(); + for (int i = 1; i <= 10; i++) { + System.out.print(" " + a.fibinacii(i)); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch04/MethodOverloadingTest.java b/Example_src/Chapter1-10/src/ch04/MethodOverloadingTest.java new file mode 100644 index 0000000..20c7838 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/MethodOverloadingTest.java @@ -0,0 +1,24 @@ +package ch04; + +import java.io.*; + +class MethodOverloading { + void receive(int i) { + System.out.println("Receive one int data"); + System.out.println("i=" + i); + } + + void receive(int x, int y) { + System.out.println("Receive two int datas"); + System.out.println("x=" + x + " y=" + y); + } +} + +public class MethodOverloadingTest { + public static void main(String[] args) { + MethodOverloading mo = new MethodOverloading(); + mo.receive(1); + mo.receive(2, 3); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/OverLoadingDemo.java b/Example_src/Chapter1-10/src/ch04/OverLoadingDemo.java new file mode 100644 index 0000000..8082a2d --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/OverLoadingDemo.java @@ -0,0 +1,9 @@ +package ch04; + +public class OverLoadingDemo { + public static void main(String[] args) { + Father x = new Father(); + x.speak(); //调用无参的speak()方法 + x.speak("music"); //调用有参的speak("music")方法 + } +} diff --git a/Example_src/Chapter1-10/src/ch04/People.java b/Example_src/Chapter1-10/src/ch04/People.java new file mode 100644 index 0000000..4c56f48 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/People.java @@ -0,0 +1,38 @@ +package ch04; + +import ch04.tom.langshan.NewDate; + + +public class People { + private String name; + private NewDate birth; + + public static void main(String[] args) { + People a = new People("XiaoYu", 1989, 10, 06); + a.output(); + } + + public People(String n1, NewDate d1) { + name = n1; + birth = d1; + } + + public People(String n1, int y, int m, int d) { + this(n1, new NewDate(y, m, d)); + } + + public People() { + this("", new NewDate()); + } + + public int age() { //计算年龄 + return NewDate.thisyear() - birth.year(); //获得年份 + } + + public void output() { + System.out.println("name : " + name); + System.out.println("birth: " + birth.toString()); + System.out.println("age : " + age()); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/PrimeNumber.java b/Example_src/Chapter1-10/src/ch04/PrimeNumber.java new file mode 100644 index 0000000..c6209d5 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/PrimeNumber.java @@ -0,0 +1,31 @@ +package ch04; + +import java.util.Scanner; + +public class PrimeNumber { + /*用(int) Math.sqrt(n)求出循环上限 + * isPrime()方法用来检测当前数是否为质数 + */ + public static boolean isPrime(int num) { + boolean prime = true; + int limit = (int) Math.sqrt(num); + for (int i = 2; i <= limit; i++) { + if (num % i == 0) { + prime = false; + break; + } + } + return prime; + } + + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.print("请输入您要判断的数:"); + int n = input.nextInt(); + if (isPrime(n)) { + System.out.println(n + "是质数!"); + } else { + System.out.println(n + "不是质数!"); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch04/PrvtVar.java b/Example_src/Chapter1-10/src/ch04/PrvtVar.java new file mode 100644 index 0000000..7cd9c6a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/PrvtVar.java @@ -0,0 +1,20 @@ +package ch04; + +public class PrvtVar { + private int money; + + PrvtVar() { + money = 2000; + } + + private int getMoney() { + return money; + } + + public static void main(String[] args) { + PrvtVar exa = new PrvtVar(); + exa.money = 3000; + int m = exa.getMoney(); //可访问本类成员的private变量 + System.out.println("money=" + m); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Rectangle.java b/Example_src/Chapter1-10/src/ch04/Rectangle.java new file mode 100644 index 0000000..970fb77 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Rectangle.java @@ -0,0 +1,29 @@ +package ch04; + +class Rectangle { //矩形类 + private int width; //矩形的宽度 + private int length; //矩形的长度 + + Rectangle() { //矩形的不带参数的构造函数,缺省的给出长(30)和宽(20) + length = 30; + width = 20; + } + + Rectangle(int l, int w) { //矩形的带参数的构造函数 + length = l; + width = w; + } + + Rectangle(Rectangle r) { //此构造方法以另一个Rectangle作为参数 + width = r.width(); //通过对象调用函数并附值给相应变量 + length = r.length(); + } + + int width() { //返回宽度 + return width; + } + + int length() { //返回长度 + return length; + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch04/RedButton.java b/Example_src/Chapter1-10/src/ch04/RedButton.java new file mode 100644 index 0000000..c03ed73 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/RedButton.java @@ -0,0 +1,18 @@ +package ch04; + +import java.applet.Applet; +import java.awt.*; + +public class RedButton extends Applet { + Button redbutton; + + public void init() { + redbutton = new Button("我是一个红色的按钮"); + redbutton.setBackground(Color.red); + add(redbutton); + } + + public void paint(Graphics g) { + g.drawString("it is a button", 30, 50); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/ShowStudent.java b/Example_src/Chapter1-10/src/ch04/ShowStudent.java new file mode 100644 index 0000000..c9ec7e4 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/ShowStudent.java @@ -0,0 +1,40 @@ +package ch04; + +class Student { + int number, tel = 81238888; + String name; + + Student(int number, String name) { + this.number = number; + this.name = name; + System.out.println("Father构造:I am " + name + "my number is " + number); + } + + void show() { + System.out.println("father's show(tel): tel of Student is " + tel); + } +} + +class Univer_Student extends Student { + boolean 婚否; + int tel = 81236666; + + Univer_Student(int number, String name, boolean b) { + super(number, name); // 使用父类的构造方法 + 婚否 = b; + System.out.println("Son构造新增属性:婚否=" + 婚否); + } + + void showtel() { + System.out.println("Son's showtel(tel):tel of Univer_Student is " + tel); + System.out.println("Son's showtel(super.tel):tel of super is " + super.tel); + } +} + +public class ShowStudent { + public static void main(String[] args) { + Univer_Student zhang = new Univer_Student(8030410, " XiaoBin,", false); + zhang.showtel(); + zhang.show(); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/SubBoy.java b/Example_src/Chapter1-10/src/ch04/SubBoy.java new file mode 100644 index 0000000..10449f3 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/SubBoy.java @@ -0,0 +1,38 @@ +package ch04; + +import java.applet.*; +import java.awt.*; + +class Father1 { + private int money; + float weight, height; + String head; + + String speak(String s) { + return s; + } +} + +class Son extends Father1 { + String hand, foot; +} + +public class SubBoy extends Applet { + Son boy; + + public void init() { + boy = new Son(); + boy.weight = 120f; + boy.height = 1.75f; + boy.head = "一个聪明的大脑袋,"; + boy.hand = "两只巧手,"; + boy.foot = "一双喜欢瞎跑的脚。"; + } + + public void paint(Graphics g) { + g.drawString(boy.speak("我是儿子"), 5, 20); + g.drawString(boy.head + boy.hand + boy.foot, 5, 40); + g.drawString("体重:" + boy.weight + " 身高:" + boy.height, 5, 60); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/Taper.java b/Example_src/Chapter1-10/src/ch04/Taper.java new file mode 100644 index 0000000..58a185d --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Taper.java @@ -0,0 +1,58 @@ +package ch04; + +class 圆 { + double 半径; + + 圆(double r) { + 半径 = r; + } + + double 计算面积() { + return 3.14 * 半径 * 半径; + } + + void 修改半径(double 新半径) { + 半径 = 新半径; + } + + double 获取半径() { + return 半径; + } +} + +class 圆锥 { + 圆 底圆; + double 高; + + 圆锥(圆 circle, double h) { + this.底圆 = circle; + this.高 = h; + } + + double 计算体积() { + double volume; + volume = 底圆.计算面积() * 高 / 3.0; + return volume; + } + + void 修改底圆半径(double r) { + 底圆.修改半径(r); + } + + double 获取底圆半径() { + return 底圆.获取半径(); + } +} + +public class Taper { + public static void main(String args[]) { + 圆 circle = new 圆(10); + 圆锥 circular = new 圆锥(circle, 20); + System.out.println("圆锥底圆半径:" + circular.获取底圆半径()); + System.out.println("圆锥的体积:" + circular.计算体积()); + circular.修改底圆半径(100); + System.out.println("圆锥底圆半径:" + circular.获取底圆半径()); + System.out.println("圆锥的体积:" + circular.计算体积()); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/TempConverter.java b/Example_src/Chapter1-10/src/ch04/TempConverter.java new file mode 100644 index 0000000..71f8ada --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/TempConverter.java @@ -0,0 +1,20 @@ +package ch04; + +public class TempConverter { + + public static void main(String[] args) { + TempConverter t = new TempConverter(); + t.data(); + } + + protected void data() { + for (int i = -40; i <= 120; i += 10) { + float c = (i - 32) * (5f / 9); + print(i, c); + } + } + + protected void print(float f, float c) { + System.out.println("华氏温度" + f + "=摄氏温度" + c); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/TestAddChengji.java b/Example_src/Chapter1-10/src/ch04/TestAddChengji.java new file mode 100644 index 0000000..aa03965 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/TestAddChengji.java @@ -0,0 +1,29 @@ +package ch04; + +import java.applet.*; +import java.awt.*; + +class Chengji { + float fun(float x, float y) { + return x * y; + } +} + +class AddChengji extends Chengji { + float fun(float x, float y) { + return x + y; + } +} + +public class TestAddChengji extends Applet { + AddChengji sum; + + public void init() { + sum = new AddChengji(); + } + + public void paint(Graphics g) { + g.drawString("sum=" + sum.fun(4, 6), 100, 40); + } +} + diff --git a/Example_src/Chapter1-10/src/ch04/TestPoint.java b/Example_src/Chapter1-10/src/ch04/TestPoint.java new file mode 100644 index 0000000..fd2bae7 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/TestPoint.java @@ -0,0 +1,23 @@ +package ch04; + +class Point { + int x, y; + + Point() { + x = 0; + y = 0; + } + + Point(int x, int y) { + this.x = x; + this.y = y; + } +} + +public class TestPoint { + public static void main(String[] args) { + Point p1 = new Point(34, 56); + Point p2 = new Point(21, 67); + p1 = p2; + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Text1.java b/Example_src/Chapter1-10/src/ch04/Text1.java new file mode 100644 index 0000000..24c9132 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Text1.java @@ -0,0 +1,28 @@ +package ch04; + +class Text1 { + static int a; //当被定义为static类型时,为类变量,可被对象或类调用 + int b; //对象变量,只能被对象调用 + + public void display(int a, int b) { //成员方法 + System.out.println("static int a=" + a); + System.out.println(" int b=" + b); + } + + public static void display(int b) { + System.out.println("static display: int b=" + b); + } + + public static void main(String args[]) { + Text1 tt = new Text1(); + tt.display(5, 6); + //Text1.display(5,6)是错误的,对象变量或对象方法只能被对象tt调用 + Text1.display(0); + //当被定义为static类型时,为类方法,可被对象或类调用 + tt.display(23); + tt.a = 9; + Text1.a = 24; + tt.b = 3; + tt.display(a, 15); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/Tongji.java b/Example_src/Chapter1-10/src/ch04/Tongji.java new file mode 100644 index 0000000..5f47aba --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/Tongji.java @@ -0,0 +1,22 @@ +package ch04; + +import java.applet.*; +import java.awt.*; + +class Tongji { + protected float fun(float x, float y) { + return x * y; + } +} + +class Addxy extends Tongji { + // float fun(float x,float y) { //非法,因为降低了访问级别 + // return x+y ; + // } +} + +class Subxy extends Tongji { + public float fun(float x, float y) { //合法,没有降低访问级别. + return x - y; + } +} diff --git a/Example_src/Chapter1-10/src/ch04/sun/com/Jerry.java b/Example_src/Chapter1-10/src/ch04/sun/com/Jerry.java new file mode 100644 index 0000000..3fa913b --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/sun/com/Jerry.java @@ -0,0 +1,19 @@ +package ch04.sun.com; + +import ch04.tom.langshan.Father; + +public class Jerry extends Father { //Jerry和Father在不同的包中. + public Jerry() { + super(20); + } + + public static void main(String[] args) { + Jerry jerry = new Jerry(); + // jerry.height=12; //非法,因为Jerry没有继承友好的height. + jerry.weight = 200; //合法. + jerry.money = 800; //合法. + int m = jerry.getMoney(); //合法.. + // jerry.setMoney(300); //非法,因为Jerry没有继承友好的方法setMoney. + System.out.println("m=" + m); + } +} diff --git a/Example_src/Chapter1-10/src/ch04/tom/langshan/Father.java b/Example_src/Chapter1-10/src/ch04/tom/langshan/Father.java new file mode 100644 index 0000000..777cd47 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/tom/langshan/Father.java @@ -0,0 +1,19 @@ +package ch04.tom.langshan; + +public class Father { + int height; + protected int money; + public int weight; + + public Father(int m) { + money = m; + } + + protected int getMoney() { + return money; + } + + void setMoney(int newMoney) { + money = newMoney; + } +} diff --git a/Example_src/Chapter1-10/src/ch04/tom/langshan/NewDate.java b/Example_src/Chapter1-10/src/ch04/tom/langshan/NewDate.java new file mode 100644 index 0000000..eea73a2 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch04/tom/langshan/NewDate.java @@ -0,0 +1,29 @@ +package ch04.tom.langshan; + +import java.util.*; //引用java.util包 + +public class NewDate { + private int year, month, day; + + public NewDate(int y, int m, int d) { + year = y; + month = (((m >= 1) & (m <= 12)) ? m : 1); + day = (((d >= 1) & (d <= 31)) ? d : 1); + } + + public NewDate() { + this(0, 0, 0); + } + + public static int thisyear() { //获得当年的年份 + return Calendar.getInstance().get(Calendar.YEAR); + } + + public int year() { //获得年份 + return year; + } + + public String toString() { //转化为字符串 + return year + "-" + month + "-" + day; + } +} diff --git a/Example_src/Chapter1-10/src/ch05/BackInterface.java b/Example_src/Chapter1-10/src/ch05/BackInterface.java new file mode 100644 index 0000000..c73e8a1 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/BackInterface.java @@ -0,0 +1,27 @@ +package ch05; + +interface People { + void peopleList(); +} + +class Student implements People { + public void peopleList() { + System.out.println("I’m a student."); + } +} + +class Teacher implements People { + public void peopleList() { + System.out.println("I’m a teacher."); + } +} + +public class BackInterface { + public static void main(String[] args) { + People a; // 声明接口变量 + a = new Student(); // 实例化,接口变量中存放对象的引用 + a.peopleList(); // 接口回调 + a = new Teacher(); // 实例化,接口变量中存放对象的引用 + a.peopleList(); // 接口回调 + } +} diff --git a/Example_src/Chapter1-10/src/ch05/CommonLader.java b/Example_src/Chapter1-10/src/ch05/CommonLader.java new file mode 100644 index 0000000..a347c9f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/CommonLader.java @@ -0,0 +1,31 @@ +package ch05; + +class 梯形 { + float 上底, 高; + static float 下底; + + 梯形(float x, float y, float h) { + 上底 = x; + 下底 = y; + 高 = h; + } + + float 获取下底() { + return 下底; + } + + void 修改下底(float b) { + 下底 = b; + } +} + +public class CommonLader { + public static void main(String[] args) { + 梯形 laderOne = new 梯形(3.0f, 10.0f, 20), laderTwo = new 梯形(2.0f, 3.0f, 10); + System.out.println("laderOne的下底:" + laderOne.获取下底()); + System.out.println("laderTwo的下底:" + laderTwo.获取下底()); + laderTwo.修改下底(60); + System.out.println("laderOne的下底:" + laderOne.获取下底()); + System.out.println("laderTwo的下底:" + laderTwo.获取下底()); + } +} diff --git a/Example_src/Chapter1-10/src/ch05/ExampleInterface.java b/Example_src/Chapter1-10/src/ch05/ExampleInterface.java new file mode 100644 index 0000000..e8b4eca --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/ExampleInterface.java @@ -0,0 +1,35 @@ +package ch05; + +interface 收费 { + public void 收取费用(); +} + +class 公共汽车 implements 收费 { + public void 收取费用() { + System.out.println("公共汽车:一元/张,不计算公里数"); + } +} + +class 出租车 implements 收费 { + public void 收取费用() { + System.out.println("出租车:1.60元/公里,起价3公里"); + } +} + +class 电影院 implements 收费 { + public void 收取费用() { + System.out.println("电影院:门票,十元/张"); + } +} + +class ExampleInterface { + public static void main(String[] args) { + 公共汽车 七路 = new 公共汽车(); + 出租车 大众 = new 出租车(); + 电影院 更俗剧场 = new 电影院(); + 七路.收取费用(); + 大众.收取费用(); + 更俗剧场.收取费用(); + + } +} diff --git a/Example_src/Chapter1-10/src/ch05/MemberTest.java b/Example_src/Chapter1-10/src/ch05/MemberTest.java new file mode 100644 index 0000000..170e985 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/MemberTest.java @@ -0,0 +1,38 @@ +package ch05; + +class Member { + static int classVar; + int instanceVar; + + static void setClassVar(int i) { + classVar = i; +// instanceVar=i; // 类方法不能访问实例变量 + } + + static int getClassVar() { + return classVar; + } + + void setInstanceVar(int i) { + classVar = i; //实例方法不但可以访问类变量,也可以实例变量 + instanceVar = i; + } + + int getInstanceVar() { + return instanceVar; + } +} + +public class MemberTest { + public static void main(String[] args) { + Member m1 = new Member(); + Member m2 = new Member(); + m1.setClassVar(1); + m2.setClassVar(2); + System.out.println("m1.classVar=" + m1.getClassVar() + " m2.ClassVar=" + m2.getClassVar()); + m1.setInstanceVar(11); + m2.setInstanceVar(22); + System.out.println("m1.InstanceVar=" + m1.getInstanceVar() + " m2.InstanceVar=" + m2.getInstanceVar()); + } +} + diff --git a/Example_src/Chapter1-10/src/ch05/Rectangle.java b/Example_src/Chapter1-10/src/ch05/Rectangle.java new file mode 100644 index 0000000..bdf4292 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/Rectangle.java @@ -0,0 +1,21 @@ +package ch05; + +class Rectangle { //矩形类 + int width; // 矩形的宽 + + int usethis(int width) { //返回宽度的函数 + this.width = width; //指自己这个对象 + return width; + } + + int unusethis(int width) { + int w = width; + return w; + } + + public static void main(String[] args) { + Rectangle r = new Rectangle(); //类对象的实例化 + System.out.println("r.width=" + r.width + " r.usethis(1)=" + r.usethis(1) + " r.width=" + r.width); + System.out.println("r.width=" + r.width + " r.unusethis(2)=" + r.unusethis(2) + " r.width=" + r.width); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch05/ShapeArea.java b/Example_src/Chapter1-10/src/ch05/ShapeArea.java new file mode 100644 index 0000000..bd540da --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/ShapeArea.java @@ -0,0 +1,58 @@ +package ch05; + +abstract class 图形 { + public abstract double 求面积(); +} + +class 梯形1 extends 图形 { + double a, b, h; + 梯形1(double a, double b, double h) { + this.a = a; + this.b = b; + this.h = h; + } + public double 求面积() { + return ((1 / 2.0) * (a + b) * h); + } +} + +class 圆形 extends 图形 { + double r; + 圆形(double r) { + this.r = r; + } + public double 求面积() { + return (3.14 * r * r); + } +} + +class 堆 { + 图形 底; + double 高; + 堆(图形 底, double 高) { + this.底 = 底; + this.高 = 高; + } + void 换底(图形 底) { + this.底 = 底; + } + public double 求体积() { + return (底.求面积() * 高) / 3.0; + } +} + +public class ShapeArea { + public static void main(String[] args) { + 堆 zui; + 图形 tuxing; + tuxing = new 梯形1(2.0, 7.0, 10.7); + System.out.println("梯形的面积" + tuxing.求面积()); + zui = new 堆(tuxing, 30); + System.out.println("梯形底的堆的体积" + zui.求体积()); + tuxing = new 圆形(10); + System.out.println("半径是10的圆的面积" + tuxing.求面积()); + zui.换底(tuxing); + System.out.println("圆形底的堆的体积" + zui.求体积()); + } +} + diff --git a/Example_src/Chapter1-10/src/ch05/StaticImportTest.java b/Example_src/Chapter1-10/src/ch05/StaticImportTest.java new file mode 100644 index 0000000..20d00fa --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/StaticImportTest.java @@ -0,0 +1,16 @@ +package ch05; + +import static java.lang.Math.sqrt; //导入静态方法sqrt() +import static java.lang.Math.pow; //导入静态方法pow() + +class Hypot { + public static void main(String args[]) { + double side1, side2; + double hypot; + side1 = 3.0; + side2 = 4.0; + // 静态导入后,不再需要通过类名Math来调用方法sqrt()和pow() + hypot = sqrt(pow(side1, 2) + pow(side2, 2)); + System.out.println("给定RT△的两边边长为:" + side1 + "和" + side2 + ",其斜边边长为:" + hypot); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch05/Stu1.java b/Example_src/Chapter1-10/src/ch05/Stu1.java new file mode 100644 index 0000000..27deedc --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/Stu1.java @@ -0,0 +1,27 @@ +package ch05; + +public class Stu1 implements Student_info //实现学生情况接口 +{ + String name; + int birth_year; //类自己的成员变量 + + public Stu1(String n1, int y) { + name = n1; + birth_year = y; + } + + public int age() //实现接口的方法 + { + return year - birth_year; + } + + public void output() //实现接口的方法 + { + System.out.println(this.name + " " + this.age() + "岁"); + } + + public static void main(String[] args) { + Stu1 s1 = new Stu1("李明", 1980); + s1.output(); + } +} diff --git a/Example_src/Chapter1-10/src/ch05/Student_info.java b/Example_src/Chapter1-10/src/ch05/Student_info.java new file mode 100644 index 0000000..aba3f1f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/Student_info.java @@ -0,0 +1,9 @@ +package ch05; + +interface Student_info { + int year = 2002; + + int age(); + + void output(); +} diff --git a/Example_src/Chapter1-10/src/ch05/SuperDemo.java b/Example_src/Chapter1-10/src/ch05/SuperDemo.java new file mode 100644 index 0000000..cbd5020 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/SuperDemo.java @@ -0,0 +1,40 @@ +package ch05; + +import java.io.*; + +class SuperClass { //定义父类 + int x; + SuperClass() { //父类的构造方法 + x = 10; + } + void doClass() { + System.out.println("SuperClass.doClass()"); + } +} + +class SubClass extends SuperClass { //定义子类 + int x; + SubClass() { //子类的构造方法 + super(); //调用父类的构造方法 + x = 100; + } + void doClass() { //重写父类的doClass方法 + System.out.println("SubClass.doClass()"); + } + void doDemo() { //演示super和this的方法 + int x; + x = 1000; + super.doClass(); //调用父类的doClass方法 + doClass(); //调用本类的doClass方法 + System.out.println("super.x=" + super.x); //父类的x + System.out.println("this.x=" + this.x); //本类的x + System.out.println("x=" + x); //本方法的x + } +} + +public class SuperDemo { + public static void main(String[] args) { //主方法 + SubClass s = new SubClass(); + s.doDemo(); + } +} diff --git a/Example_src/Chapter1-10/src/ch05/TestAbstract.java b/Example_src/Chapter1-10/src/ch05/TestAbstract.java new file mode 100644 index 0000000..a1b5177 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/TestAbstract.java @@ -0,0 +1,22 @@ +package ch05; + +abstract class C { + abstract void callme(); + void metoo() { + System.out.println("Inside C's metoo( ) method"); + } +} + +class D extends C { + void callme() { + System.out.println("Inside D's callme( ) method"); + } +} + +public class TestAbstract { + public static void main(String[] args) { + C c = new D(); + c.callme(); + c.metoo(); + } +} diff --git a/Example_src/Chapter1-10/src/ch05/TestInterface.java b/Example_src/Chapter1-10/src/ch05/TestInterface.java new file mode 100644 index 0000000..47eddff --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/TestInterface.java @@ -0,0 +1,53 @@ +package ch05; + +import java.applet.*; +import java.awt.*; + +interface Computable { + final int MAX = 100; + void speak(String s); + int f(int x); + float g(float x, float y); +} + +class China implements Computable { + int xuehao; + public int f(int x) { //不要忘记public关键字. + int sum = 0; + for (int i = 1; i <= x; i++) { + sum = sum + i; + } + return sum; + } + public float g(float x, float y) { + return 6; //至少有return语句. + } + public void speak(String s) { + } +} + +class Japan implements Computable { + int xuehao; + public int f(int x) { + return 68; + } + public float g(float x, float y) { + return x + y; + } + public void speak(String s) { + //必须有方法体,但体内可以没有任何语句. + } +} + +public class TestInterface { + public static void main(String[] args) { + China Li; + Japan Henlu; + Li = new China(); + Henlu = new Japan(); + Li.xuehao = 991898; + Henlu.xuehao = 941448; + System.out.println("学号:" + Li.MAX + Li.xuehao + "从1到100 求和" + Li.f(100)); + System.out.println("学号:" + Henlu.MAX + Henlu.xuehao + "加法" + Henlu.g(2.0f, 3.0f)); + } +} diff --git a/Example_src/Chapter1-10/src/ch05/Triangle.java b/Example_src/Chapter1-10/src/ch05/Triangle.java new file mode 100644 index 0000000..5895e17 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch05/Triangle.java @@ -0,0 +1,22 @@ +package ch05; + +class 三角形 { + double a, b, c; + + 三角形(double a, double b, double c) { + setABC(this, a, b, c); + } + + void setABC(三角形 trangle, double a, double b, double c) { + trangle.a = a; + trangle.b = b; + trangle.c = c; + } +} + +class Triangle { + public static void main(String[] args) { + 三角形 tra = new 三角形(3, 4, 5); + System.out.print("三角形型的三边是:" + tra.a + "," + tra.b + "," + tra.c + ","); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/ArrGen.java b/Example_src/Chapter1-10/src/ch06/ArrGen.java new file mode 100644 index 0000000..0e30f6a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/ArrGen.java @@ -0,0 +1,48 @@ +package ch06; + +import java.util.ArrayList; +import java.util.List; + +class Student { + private String name; + private int score; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + public Student(String name, int score) { + super(); + this.name = name; + this.score = score; + } + + public String toString() { + return name + "的成绩为:" + score + "分"; + } +} + +public class ArrGen { + public static void main(String[] args) { + Student stu1 = new Student("Smith", 70); + Student stu2 = new Student("John", 89); + List newsStu = new ArrayList(); + newsStu.add(stu1); + newsStu.add(stu2); + for (Student s : newsStu) { + System.out.println(s); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch06/ArrayListExample.java b/Example_src/Chapter1-10/src/ch06/ArrayListExample.java new file mode 100644 index 0000000..bdfdf9d --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/ArrayListExample.java @@ -0,0 +1,19 @@ +package ch06; + +import java.util.*; + +public class ArrayListExample { + public static void main(String[] args) { + List list = new ArrayList(); + list.add("1"); + list.add("2"); + list.add(2, "3"); + System.out.println("list集合有" + list.size() + "个元素"); + list.remove(1); + System.out.println("删除一个元素后,list集合有" + list.size() + "个元素"); + if (list.contains("3")) { + System.out.println("集合中存在元素\"3\""); + } + System.out.println("\"1\"的索引位置是:" + list.indexOf("1")); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/CalendarExample.java b/Example_src/Chapter1-10/src/ch06/CalendarExample.java new file mode 100644 index 0000000..ea2bd72 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/CalendarExample.java @@ -0,0 +1,21 @@ +package ch06; + +import java.util.Calendar; + +public class CalendarExample { + public static void main(String[] args) { + Calendar cal = Calendar.getInstance(); + System.out.println("当前的日期和时间:"); + System.out.print("年-月-日 "); + System.out.println("时:分:秒"); + System.out.print(cal.get(Calendar.YEAR) + "-"); + System.out.print(cal.get(Calendar.MONTH) + "-"); + System.out.print(cal.get(Calendar.DATE) + " "); + System.out.print(cal.get(Calendar.HOUR) + ":"); + System.out.print(cal.get(Calendar.MINUTE) + ":"); + System.out.println(cal.get(Calendar.SECOND)); + cal.add(Calendar.DATE, 5); + System.out.print("5天后是"); + System.out.println(cal.get(Calendar.DATE) + "日"); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/CompareString.java b/Example_src/Chapter1-10/src/ch06/CompareString.java new file mode 100644 index 0000000..0938820 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/CompareString.java @@ -0,0 +1,20 @@ +package ch06; + +//使用两种方法,比较两个字符串是否相等 +public class CompareString { + public static void main(String[] args) { + String str1 = new String("We are happy!"); + String str2 = new String("We are happy!"); + System.out.println("使用==运算符比较时:"); + if (str1 == str2) + System.out.println("两个字符串相等"); + else + System.out.println("两个字符串不相等"); + System.out.println(); + System.out.println("使用equals()方法比较时:"); + if (str1.equals(str2)) + System.out.println("两个字符串相等"); + else + System.out.println("两个字符串不相等"); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/DateExample.java b/Example_src/Chapter1-10/src/ch06/DateExample.java new file mode 100644 index 0000000..a2b7bea --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/DateExample.java @@ -0,0 +1,15 @@ +package ch06; + +import java.util.Date; + +public class DateExample { + public static void main(String[] args) { + Date dt = new Date(); + System.out.println("今天的日期是:" + dt); //A + String strDate = dt.toString(); //B + String strMonth = strDate.substring(4, 7); //C + System.out.println("现在的月份是:" + strMonth); + String strTime = strDate.substring(11, 19); //D + System.out.println("当前的时间是:" + strTime); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/EnvExample.java b/Example_src/Chapter1-10/src/ch06/EnvExample.java new file mode 100644 index 0000000..4c877f9 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/EnvExample.java @@ -0,0 +1,16 @@ +package ch06; + +public class EnvExample { + public static void main(String[] args) { + double d1 = 3.2; + Double objd1 = new Double(d1); + Double objd2 = new Double("3.2"); + System.out.println("最大的double值" + Double.MAX_VALUE); + System.out.println("最小的double值" + Double.MIN_VALUE); + System.out.println("将字符串转换成double值" + Double.parseDouble("23.2")); + + System.out.println("Double对象中封装的值:" + objd1.doubleValue()); + System.out.println("比较objd1==objd2:" + (objd1 == objd2)); + System.out.println("比较objd1.equals(objd2):" + objd1.equals(objd2)); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/HashMapExample.java b/Example_src/Chapter1-10/src/ch06/HashMapExample.java new file mode 100644 index 0000000..76e69f3 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/HashMapExample.java @@ -0,0 +1,20 @@ +package ch06; + +import java.util.HashMap; +import java.util.Map; + +public class HashMapExample { + public static void main(String[] args) { + Map map = new HashMap(); + map.put("one", "一"); + map.put("two", "二"); + map.put("three", "三"); + System.out.println(map.get("one")); //A + System.out.println(map.values()); //B + map.put("three", "3"); //C + System.out.println(map.values()); //D + System.out.println("删除前的键集" + map.keySet()); //E + map.remove("one"); //F + System.out.println("删除后的键集" + map.keySet()); //G + } +} diff --git a/Example_src/Chapter1-10/src/ch06/HashMapExampleEdit.java b/Example_src/Chapter1-10/src/ch06/HashMapExampleEdit.java new file mode 100644 index 0000000..302030a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/HashMapExampleEdit.java @@ -0,0 +1,26 @@ +package ch06; + +import java.util.HashMap; +import java.util.Map; + +public class HashMapExampleEdit { + public static void main(String[] args) { + Map map = new HashMap(); + map.put("one", "一"); + map.put("two", "二"); + map.put("three", "三"); + System.out.println(map.get("one")); + System.out.println(map.values()); + map.put("three", "3"); + System.out.println(map.values()); + System.out.println("删除前的键集" + map.keySet()); + map.remove("one"); + System.out.println("删除后的键集" + map.keySet()); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + System.out.println("key=" + key + ", value=" + value); + } + + } +} diff --git a/Example_src/Chapter1-10/src/ch06/HashSetExample.java b/Example_src/Chapter1-10/src/ch06/HashSetExample.java new file mode 100644 index 0000000..1a45021 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/HashSetExample.java @@ -0,0 +1,21 @@ +package ch06; + +import java.util.*; + +public class HashSetExample { + public static void main(String[] args) { + Set set = new HashSet(); + + set.add("1"); + set.add("2"); + set.add("3"); + + set.add(new Integer(2)); + set.add(new Double(3.2)); + + set.add("3"); + + System.out.println("set集合的元素个数为:" + set.size() + "个"); + System.out.println("set集合的元素分别为:" + set.toString()); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/SimpleDateExample.java b/Example_src/Chapter1-10/src/ch06/SimpleDateExample.java new file mode 100644 index 0000000..9019a96 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/SimpleDateExample.java @@ -0,0 +1,16 @@ +package ch06; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class SimpleDateExample { + public static void main(String[] args) throws Exception { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //A + Date dt = sdf.parse("2009-8-30"); //B + System.out.println("英文格式:" + dt); + System.out.println(); + sdf.applyPattern("yyyy年MM月dd日"); //C + String str = sdf.format(dt); //D + System.out.println("中文格式:" + str); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/TotalMoney.java b/Example_src/Chapter1-10/src/ch06/TotalMoney.java new file mode 100644 index 0000000..773a951 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/TotalMoney.java @@ -0,0 +1,20 @@ +package ch06; + +import java.util.Scanner; + +public class TotalMoney { + public static void main(String[] args) { + double totalMon, UnitPrice; + int num; + Scanner sc = new Scanner(System.in); + System.out.println("依次输入单价、数量,并以/分隔:"); + + String str = sc.nextLine(); + Scanner scan = new Scanner(str); + scan.useDelimiter("/"); + UnitPrice = scan.nextDouble(); + num = scan.nextInt(); + totalMon = UnitPrice * num; + System.out.println("总金额为:" + totalMon); + } +} diff --git a/Example_src/Chapter1-10/src/ch06/extractAndsearch.java b/Example_src/Chapter1-10/src/ch06/extractAndsearch.java new file mode 100644 index 0000000..d3aa758 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch06/extractAndsearch.java @@ -0,0 +1,19 @@ +package ch06; + +public class extractAndsearch { + public static void main(String[] args) { + String str1 = new String("中华人民共和国60周年庆"); + String str2 = new String(" 国庆大阅兵 "); + int loc1 = str1.indexOf('国'); + int loc2 = str1.indexOf("人民"); + int loc3 = str1.lastIndexOf('人'); + int loc4 = str1.lastIndexOf("60"); + System.out.println("loc1=" + loc1); + System.out.println("loc2=" + loc2); + System.out.println("loc3=" + loc3); + System.out.println("loc4=" + loc4); + + System.out.println(str2.substring(2)); + System.out.println(str2.substring(3, 6)); + } +} diff --git a/Example_src/Chapter1-10/src/ch07/ComputeAvg.java b/Example_src/Chapter1-10/src/ch07/ComputeAvg.java new file mode 100644 index 0000000..7cdd830 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch07/ComputeAvg.java @@ -0,0 +1,26 @@ +package ch07; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class ComputeAvg { + public static void main(String[] args) { + int score, num; + double avg; + Scanner in = new Scanner(System.in); + try { + System.out.println("请输入总分:"); + score = in.nextInt(); + System.out.println("请输入人数:"); + num = in.nextInt(); + avg = score / num; + System.out.println("平均成绩为:" + avg); + } catch (InputMismatchException e1) { + System.out.println("输入不是数字!"); + } catch (ArithmeticException e2) { + System.out.println("人数不能为0"); + } catch (Exception e3) { + System.out.println("其他异常:"); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch07/ExceptionTest.java b/Example_src/Chapter1-10/src/ch07/ExceptionTest.java new file mode 100644 index 0000000..41fb9f1 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch07/ExceptionTest.java @@ -0,0 +1,40 @@ +package ch07; + +import java.util.Scanner; + +class MyException extends Exception { //继承Exception类 + private String myString; + + public MyException(String myString) { + + this.myString = myString; + } + + public String getMyString() { + return myString; + } + + @Override + public String toString() { //重写了类的方法 + return myString; + } +} + +public class ExceptionTest { + public static void main(String[] args) { + double i, j; + Scanner scan = new Scanner(System.in); + System.out.println("请输入分子:"); + i = scan.nextDouble(); + System.out.println("请输入分母"); + j = scan.nextDouble(); + try { + if (j == 0) { //判断分母的值 + throw new MyException("除数不能零!"); //A + } else + System.out.println("分数值为:" + i + "/" + j + "=" + (i / j)); + } catch (MyException e) { + System.out.println(e); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch07/checkDemo.java b/Example_src/Chapter1-10/src/ch07/checkDemo.java new file mode 100644 index 0000000..ccc0286 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch07/checkDemo.java @@ -0,0 +1,23 @@ +package ch07; + +import java.util.Scanner; + +public class checkDemo { + public static void check() { + Scanner in = new Scanner(System.in); + System.out.println("请输入商品的书目:"); + int num = in.nextInt(); + if (num < 0) + throw new NumberFormatException("商品书目不能小于0!"); + else + System.out.println("商品数目为:" + num); + } + + public static void main(String[] args) { + try { + check(); + } catch (Exception e) { + System.out.println("异常:" + e.getMessage()); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch07/throwsDemo.java b/Example_src/Chapter1-10/src/ch07/throwsDemo.java new file mode 100644 index 0000000..62c76c6 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch07/throwsDemo.java @@ -0,0 +1,26 @@ +package ch07; + +import java.io.IOException; +import java.util.Scanner; + +public class throwsDemo { + public static void test() throws NullPointerException, IOException { + System.out.println("请输入一个数字(0,1):"); + Scanner in = new Scanner(System.in); + int flag = in.nextInt(); + if (flag == 1) + throw new NullPointerException(); + else + throw new IOException(); + } + + public static void main(String[] args) { + try { + test(); + } catch (NullPointerException e) { + System.out.println("系统抛出了" + e.getClass() + "类型的异常"); + } catch (IOException e) { + System.out.println("系统抛出了" + e.getClass() + "类型的异常"); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch08/FileAndDirectoryTest.java b/Example_src/Chapter1-10/src/ch08/FileAndDirectoryTest.java new file mode 100644 index 0000000..e0c3e37 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch08/FileAndDirectoryTest.java @@ -0,0 +1,26 @@ +package ch08; + +import java.io.File; + + +public class FileAndDirectoryTest { + public static void main(String[] args) { + String filename = "testFile"; + File f1 = new File(filename); //A + System.out.println(filename + "是否存在:" + f1.exists()); + System.out.println(filename + "是文件吗:" + f1.isFile()); + System.out.println(filename + "最后修改时间:" + f1.lastModified()); + System.out.println(filename + "文件大小:" + f1.length()); + + String direname = "testDire"; + File f2 = new File(direname); //B + System.out.println(direname + "的绝对路径:" + f2.getAbsolutePath()); + if (f2.isDirectory()) { //C + String[] fileList = f2.list(); //D + System.out.println(direname + "目录中的文件和目录包括:"); + for (int i = 0; i < fileList.length; i++) + System.out.print(fileList[i] + " "); + } + } + +} diff --git a/Example_src/Chapter1-10/src/ch08/FileInExample.java b/Example_src/Chapter1-10/src/ch08/FileInExample.java new file mode 100644 index 0000000..5574fb9 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch08/FileInExample.java @@ -0,0 +1,25 @@ +package ch08; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +public class FileInExample { + public static void main(String[] args) { + int rs; + byte b[] = new byte[10]; + try { + File f = new File("C:\\in.txt"); + FileInputStream fis = new FileInputStream(f); + rs = fis.read(b, 0, 10); + while (rs > 0) { + String s = new String(b, 0, rs); + System.out.print(s); + rs = fis.read(b, 0, 10); + } + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch08/FileOutExample.java b/Example_src/Chapter1-10/src/ch08/FileOutExample.java new file mode 100644 index 0000000..4baec28 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch08/FileOutExample.java @@ -0,0 +1,28 @@ +package ch08; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + + +public class FileOutExample { + public static void main(String[] args) { + int rs; + byte b[] = new byte[10]; + try { + FileInputStream fis = new FileInputStream("notepad.exe"); + FileOutputStream fos = new FileOutputStream("note.exe"); + System.out.println("��ʼ�����ļ������Ժ�......"); + rs = fis.read(b, 0, 10); + while (rs > 0) { + fos.write(b, 0, 10); + rs = fis.read(b, 0, 10); + } + System.out.println("�ļ�����������лл��"); + fis.close(); + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch08/ReaderExample.java b/Example_src/Chapter1-10/src/ch08/ReaderExample.java new file mode 100644 index 0000000..0e60a60 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch08/ReaderExample.java @@ -0,0 +1,25 @@ +package ch08; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +public class ReaderExample { + public static void main(String[] args) { + try { + File f = new File("java.txt"); + FileReader fr = new FileReader(f); + int len = fr.read(); + while (len >= 0) { + System.out.print((char) len); + len = fr.read(); + } + fr.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch08/WriterExample.java b/Example_src/Chapter1-10/src/ch08/WriterExample.java new file mode 100644 index 0000000..eff43cc --- /dev/null +++ b/Example_src/Chapter1-10/src/ch08/WriterExample.java @@ -0,0 +1,23 @@ +package ch08; + +import java.io.FileWriter; +import java.io.IOException; +import java.util.Random; + +public class WriterExample { + public static void main(String[] args) { + Random rand = new Random(); + try { + FileWriter fw = new FileWriter("rand.txt"); + int rs; + for (int i = 0; i < 5; i++) { + rs = rand.nextInt(2000); + fw.write(String.valueOf(rs)); + } + fw.write("JavaEE�̳�"); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch09/MyThread1.java b/Example_src/Chapter1-10/src/ch09/MyThread1.java new file mode 100644 index 0000000..a4446cc --- /dev/null +++ b/Example_src/Chapter1-10/src/ch09/MyThread1.java @@ -0,0 +1,20 @@ +package ch09; + + +public class MyThread1 extends Thread { + public static void main(String[] args) { + Thread t = Thread.currentThread(); + System.out.println("当前主线程是:" + t); + t.setName("MyThread1"); + System.out.println("当前主线程是:" + t); + MyThread1 mt = new MyThread1(); + mt.start(); + } + + public void run() { + int sum = 0; + for (int i = 0; i < 101; i++) + sum += i; + System.out.println("1+2+...+100=" + sum); + } +} diff --git a/Example_src/Chapter1-10/src/ch09/SimpleThread.java b/Example_src/Chapter1-10/src/ch09/SimpleThread.java new file mode 100644 index 0000000..691b462 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch09/SimpleThread.java @@ -0,0 +1,23 @@ +package ch09; + + +public class SimpleThread implements Runnable { + public static void main(String[] args) { + Thread t = new Thread(new SimpleThread(), "线程1"); //A + t.start(); + System.out.println("主线程运行结束"); + } + + public void run() { + int i = 1; + while (i <= 10) { + try { + System.out.print("*"); + Thread.sleep(1000); //B + } catch (InterruptedException e) { + e.printStackTrace(); + } + i++; + } + } +} diff --git a/Example_src/Chapter1-10/src/ch09/SyncExample.java b/Example_src/Chapter1-10/src/ch09/SyncExample.java new file mode 100644 index 0000000..0c5f563 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch09/SyncExample.java @@ -0,0 +1,33 @@ +package ch09; + +class PrintCH { + public static synchronized void print(char c) { + for (int i = 0; i < 4; i++) { + System.out.print(c); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} + +public class SyncExample extends Thread { + private char ch; + + public SyncExample(char ch) { + this.ch = ch; + } + + public void run() { + PrintCH.print(ch); + } + + public static void main(String[] args) { + SyncExample t1 = new SyncExample('A'); + SyncExample t2 = new SyncExample('B'); + t1.start(); + t2.start(); + } +} diff --git a/Example_src/Chapter1-10/src/ch09/SyncMassExample.java b/Example_src/Chapter1-10/src/ch09/SyncMassExample.java new file mode 100644 index 0000000..aea5a86 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch09/SyncMassExample.java @@ -0,0 +1,36 @@ +package ch09; + +class PrintCH2 { + public void print(char c) { + for (int i = 0; i < 4; i++) { + System.out.print(c); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } +} + +public class SyncMassExample extends Thread { + private char ch; + private static PrintCH2 myprint = new PrintCH2(); + + public SyncMassExample(char ch) { + this.ch = ch; + } + + public void run() { + synchronized (myprint) { //A + myprint.print(ch); + } + } + + public static void main(String[] args) { + SyncMassExample t1 = new SyncMassExample('A'); + SyncMassExample t2 = new SyncMassExample('B'); + t1.start(); + t2.start(); + } +} diff --git a/Example_src/Chapter1-10/src/ch09/WaitNotiExample.java b/Example_src/Chapter1-10/src/ch09/WaitNotiExample.java new file mode 100644 index 0000000..dec50a2 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch09/WaitNotiExample.java @@ -0,0 +1,81 @@ +package ch09; + +class ChopStick { + boolean available; + + ChopStick() { + available = true; + } + + public synchronized void takeup() { + while (!available) { + try { + System.out.println("哲学家等待另一根筷子"); + wait(); + } catch (InterruptedException e) { + } + } + available = false; + } + + public synchronized void putdown() { + available = true; + notify(); + } +} + +class Philosopher extends Thread { + ChopStick left, right; + int phio_num; + + public Philosopher(ChopStick left, ChopStick right, int phio_num) { + super(); + this.left = left; + this.right = right; + this.phio_num = phio_num; + } + + public void eat() { + left.takeup(); + right.takeup(); + System.out.println("哲学家 " + (this.phio_num + 1) + " 在用餐"); + } + + public void think() { + left.putdown(); + right.putdown(); + System.out.println("哲学家 " + (this.phio_num + 1) + " 在思考"); + } + + public void run() { + int i = 0; + while (true) { + eat(); + try { + sleep(1000); + } catch (InterruptedException e) { + } + think(); + try { + sleep(1000); + } catch (InterruptedException e) { + } + } + } +} + +public class WaitNotiExample { + public static void main(String[] args) { + final ChopStick[] chopsticks = new ChopStick[4]; + final Philosopher[] philos = new Philosopher[4]; + for (int i = 0; i < 4; i++) { + chopsticks[i] = new ChopStick(); + } + for (int i = 0; i < 4; i++) { + philos[i] = new Philosopher(chopsticks[i], chopsticks[(i + 1) % 4], i); + } + for (int i = 0; i < 4; i++) { + philos[i].start(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch10/AccountDao.java b/Example_src/Chapter1-10/src/ch10/AccountDao.java new file mode 100644 index 0000000..de6ef5f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/AccountDao.java @@ -0,0 +1,9 @@ +package ch10; + +public interface AccountDao { + public int insert(double balance, String cardNo);//添加卡号和余额 + + public int update(String id, double balance);//根据id更数据 + + public int delete(int id);//根据id删除数据 +} diff --git a/Example_src/Chapter1-10/src/ch10/AccountDaoImpl.java b/Example_src/Chapter1-10/src/ch10/AccountDaoImpl.java new file mode 100644 index 0000000..bb4c39d --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/AccountDaoImpl.java @@ -0,0 +1,67 @@ +package ch10; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class AccountDaoImpl implements AccountDao { + private Connection con; + private PreparedStatement pstmt; + + //根据id删除记录 + public int delete(int id) { + int result = 0; + con = ConnectionManager.getConnction();//得到数据库连接 + try { + String sql = "delete from account where id=?"; + pstmt = con.prepareStatement(sql); //创建PreparedStatement对象 + pstmt.setInt(1, id); + result = pstmt.executeUpdate(); //执行删除操作 + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + //添加记录 + public int insert(double balance, String cardNo) { + int result = 0; + con = ConnectionManager.getConnction();//得到数据库连接 + try { + String sql = "insert into account(balance,creditcard) values(?,?)"; + pstmt = con.prepareStatement(sql); //创建PreparedStatement对象 + pstmt.setDouble(1, balance); + pstmt.setString(2, cardNo); + result = pstmt.executeUpdate(); //执行插入操作 + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + //根据卡号修改账户余额 + public int update(String cardNo, double balance) { + int result = 0; + con = ConnectionManager.getConnction();//得到数据库连接 + try { + String sql = "update account set balance=? where creditcard=?"; + pstmt = con.prepareStatement(sql); //创建PreparedStatement对象 + pstmt.setDouble(1, balance); + pstmt.setString(2, cardNo); + result = pstmt.executeUpdate(); //执行插入操作 + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/ConnectionManager.java b/Example_src/Chapter1-10/src/ch10/ConnectionManager.java new file mode 100644 index 0000000..387e76a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/ConnectionManager.java @@ -0,0 +1,89 @@ +/* + * y2javaee.sg.ch03.ConnectionManager.java + * 2007-6-12 + * 第3章的Java示例,演示Java的JDBC的连接管理 + */ +package ch10; + +import java.sql.*; + + +public class ConnectionManager { + + private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; + + private static final String DATABASE_URL = + "jdbc:mysql://localhost:3306/books?useUnicode=true&characterEncoding=UTF-8"; + + private static final String DATABASE_USRE = "root"; + + private static final String DATABASE_PASSWORD = "root"; + + // 返回连接 + public static Connection getConnction() { + Connection dbConnection = null; + try { + Class.forName(DRIVER_CLASS); + dbConnection = DriverManager.getConnection(DATABASE_URL, + DATABASE_USRE, DATABASE_PASSWORD); + + } catch (Exception e) { + e.printStackTrace(); + } + + return dbConnection; + } + + + // 关闭连接 + public static void closeConnection(Connection dbConnection) { + try { + if (dbConnection != null && (!dbConnection.isClosed())) { + dbConnection.close(); + } + } catch (SQLException sqlEx) { + sqlEx.printStackTrace(); + } + + } + + // 关闭结果集 + public static void closeResultSet(ResultSet res) { + try { + if (res != null) { + res.close(); + res = null; + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + /** + * 关闭语句 + * + * @param pStatement PreparedStatement + */ + + public static void closePreparedStatement(PreparedStatement pStatement) { + try { + if (pStatement != null) { + pStatement.close(); + pStatement = null; + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public static void closeStatement(Statement Statement) { + try { + if (Statement != null) { + Statement.close(); + Statement = null; + } + } catch (SQLException e) { + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch10/InsertUser.java b/Example_src/Chapter1-10/src/ch10/InsertUser.java new file mode 100644 index 0000000..b18d11f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/InsertUser.java @@ -0,0 +1,34 @@ +package ch10; + +import java.sql.*; + +public class InsertUser { + private Connection con; + private PreparedStatement pstmt; + + public int insert(String name, String password) { + int result = 0; + con = ConnectionManager.getConnction();//得到数据库连接 + try { + String sql = "insert into userinfo(loginname,password) values(?,?)"; + pstmt = con.prepareStatement(sql); //创建PreparedStatement对象 + pstmt.setString(1, name); + pstmt.setString(2, password); + result = pstmt.executeUpdate(); //执行插入操作 + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + public static void main(String[] args) { + int result = new InsertUser().insert("admin1", "1111");//调用insert()方法执行插入操作 + if (result > 0) //根据result的值判断插入是否成功 + System.out.println("插入成功"); + else + System.out.println("插入失败"); + } +} diff --git a/Example_src/Chapter1-10/src/ch10/ListUser.java b/Example_src/Chapter1-10/src/ch10/ListUser.java new file mode 100644 index 0000000..ab8a0e3 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/ListUser.java @@ -0,0 +1,50 @@ +package ch10; + +import java.util.*; +import java.sql.*; + +public class ListUser { + public static void main(String[] args) {//利用数组显示数据库中记录 + // TODO Auto-generated method stub + List list = new ListUser().listAll(); + int n = list.size(); + UserInfo user = new UserInfo(); + for (int i = 0; i < n; i++) { + user = (UserInfo) list.get(i); + System.out.println(user.getUserId() + " " + + user.getLoginName() + user.getPassword()); + } + } + + public List listAll() { //得到userinfo 表的数据,并存入数组中 + UserInfo user = null; + Connection con = null; + Statement stmt = null; + ResultSet rs = null; + List list = new ArrayList();//建立一个数组对象用于存放UserInfo对象 + try { + con = ConnectionManager.getConnction(); + stmt = con.createStatement(); + rs = stmt.executeQuery("select * from userinfo");//查询字符串 + while (rs.next()) { //遍历结果集中的所有记录 + user = new UserInfo(); //创建一个UserInfo对象用于存放数组中一行数据 + //将结果集当前记录中的userId属性的值赋给对象user中的userId属性 + user.setUserId(rs.getInt("userId")); + //将结果集当前记录中的loginName属性的值赋给对象user中的loginName属性 + user.setLoginName(rs.getString("loginName")); + //将结果集当前记录中的password属性的值赋给对象user中的password属性 + user.setPassword(rs.getString("password")); + list.add(user);//将user对象添加到数组list中. + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeResultSet(rs); + ConnectionManager.closeStatement(stmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return list; + + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/ShowTitles.java b/Example_src/Chapter1-10/src/ch10/ShowTitles.java new file mode 100644 index 0000000..640e2c4 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/ShowTitles.java @@ -0,0 +1,38 @@ +package ch10; + +import java.sql.*; + + +public class ShowTitles { + private Connection connection; + private Statement titlesQuery; + private ResultSet results; + + // 显示图书信息方法 + public void getTitles() { + try { + connection = ConnectionManager.getConnction();//得到数据库连接 + titlesQuery = connection.createStatement();//创建Statement对象 + //执行SQL查询,并得到结果集 + ResultSet results = titlesQuery.executeQuery("select * from titles"); + // 在控制台打印所有图书ISBN号和书名 + while (results.next()) { + System.out.println(results.getString("isbn") + " " + results.getString("title")); + } + } + // 处理数据库异常 + catch (SQLException exception) { + exception.printStackTrace(); + } + // 释放资源 + finally { + ConnectionManager.closeResultSet(results); + ConnectionManager.closeStatement(titlesQuery); + ConnectionManager.closeConnection(connection); + } + } + + public static void main(String args[]) { + new ShowTitles().getTitles(); + } +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch10/ShowUser.java b/Example_src/Chapter1-10/src/ch10/ShowUser.java new file mode 100644 index 0000000..e36cf0f --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/ShowUser.java @@ -0,0 +1,31 @@ +package ch10; + +import java.sql.*; + +public class ShowUser { + public static void main(String[] args) { + new ShowUser().listAll(); + } + + public void listAll() { + Connection con = null; + Statement stmt = null; + ResultSet rs = null; + try { + con = ConnectionManager.getConnction();//得到一个数据库连接 + stmt = con.createStatement(); //创建Statement查询对象 + String sql = "select * from userinfo";//构造查询字符串 + rs = stmt.executeQuery(sql); //执行查询返回结果集 + System.out.println("ID" + " 用户名" + " 密码");//打印标题 + while (rs.next()) { + int id = rs.getInt("userId"); //得到userInfo表userID字段值 + String loginName = rs.getString("loginName");//得到loginName字段值 + String password = rs.getString("password");//得到password字段值 + System.out.println(id + " " + loginName + " " + password);//显示记录内容 + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/Example_src/Chapter1-10/src/ch10/TestAccount.java b/Example_src/Chapter1-10/src/ch10/TestAccount.java new file mode 100644 index 0000000..fe1ce41 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/TestAccount.java @@ -0,0 +1,20 @@ +package ch10; + +public class TestAccount { + public static void main(String[] args) { + AccountDao dao = new AccountDaoImpl(); + int n; + n = dao.insert(100000, "002");//插入卡号为001余额为10000的账户 + if (n > 0) System.out.println("插入成功"); + else + System.out.println("插入失败"); + n = dao.update("001", 200000);//将卡号为001的账户余额更改为20000 + if (n > 0) System.out.println("更新成功"); + else + System.out.println("更新失败"); + n = dao.delete(3);//删除id为2的账户信息 + if (n > 0) System.out.println("删除成功"); + else + System.out.println("删除失败"); + } +} diff --git a/Example_src/Chapter1-10/src/ch10/TestTitleDaoImpl.java b/Example_src/Chapter1-10/src/ch10/TestTitleDaoImpl.java new file mode 100644 index 0000000..37f1edb --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/TestTitleDaoImpl.java @@ -0,0 +1,24 @@ +package ch10; + +import java.util.*; + +public class TestTitleDaoImpl { + public static void main(String[] args) { + TitleDao dao = new TitleDaoImpl(); + //测试getByTitle方法 + List list = dao.getByTitle("Web"); + int n = list.size(); + Titles title = null; + System.out.println("测试getByTitle方法"); + for (int i = 0; i < n; i++) { + title = (Titles) list.get(i); + System.out.println(title.getIsbn() + " " + title.getTitle()); + } + //测试getByIsbn方法 + title = dao.getByIsbn("01234566771"); + System.out.println("测试getByIsbn方法"); + if (title != null) + System.out.println(title.getTitle()); + else System.out.println("not find"); + } +} diff --git a/Example_src/Chapter1-10/src/ch10/TitleDao.java b/Example_src/Chapter1-10/src/ch10/TitleDao.java new file mode 100644 index 0000000..80072a0 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/TitleDao.java @@ -0,0 +1,9 @@ +package ch10; + +import java.util.List; + +public interface TitleDao { + public Titles getByIsbn(String isbn); //根据ISBN进行查询 + + public List getByTitle(String title); //根据书名title进行查询 +} diff --git a/Example_src/Chapter1-10/src/ch10/TitleDaoImpl.java b/Example_src/Chapter1-10/src/ch10/TitleDaoImpl.java new file mode 100644 index 0000000..4e83fc7 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/TitleDaoImpl.java @@ -0,0 +1,90 @@ +package ch10; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +public class TitleDaoImpl implements TitleDao { + private Connection connection; + private PreparedStatement titlesQuery; + private ResultSet results; + + public int addTitle(Titles titles) { + + + return 1; + } + + // 根据title查询,返回图书列表 + public List getByTitle(String title) { + List titlesList = new ArrayList(); + // 获取书籍列表 + try { + connection = ConnectionManager.getConnction(); + String sql = "SELECT isbn, title, editionNumber, " + + "copyright, publisherID, imageFile, price " + + "FROM titles where title like '%" + title + "%' ORDER BY title"; + titlesQuery = connection.prepareStatement(sql); + + ResultSet results = titlesQuery.executeQuery(); + // 读取行数据 + while (results.next()) { + Titles book = new Titles(); //每次创建一个封装类的实例 + //将数据表中的一条记录数据添加到封装类中 + book.setIsbn(results.getString("isbn")); + book.setTitle(results.getString("title")); + book.setEditionNumber(results.getInt("editionNumber")); + book.setCopyright(results.getString("copyright")); + book.setPublisherId(results.getInt("publisherID")); + book.setImageFile(results.getString("imageFile")); + book.setPrice(results.getFloat("price")); + titlesList.add(book); //将封将类添加到数组中 + } + } + // 处理数据库异常 + catch (SQLException exception) { + exception.printStackTrace(); + } + // 释放资源 + finally { + ConnectionManager.closeResultSet(results); + ConnectionManager.closeStatement(titlesQuery); + ConnectionManager.closeConnection(connection); + } + return titlesList; + } + + //根据ISBN进行查询,返回一个Titles类的实例 + + public Titles getByIsbn(String isbn) { + connection = ConnectionManager.getConnction(); + Titles book = null; + try { + titlesQuery = connection + .prepareStatement("SELECT isbn, title, editionNumber, " + + "copyright, publisherID, imageFile, price " + + "FROM titles where isbn=" + isbn); + ResultSet results = titlesQuery.executeQuery(); + if (results.next()) { + book = new Titles(); //创建一个封装类的实例 + //将将结果集中记录数据添加到封装类中 + book.setIsbn(results.getString("isbn")); + book.setTitle(results.getString("title")); + book.setEditionNumber(results.getInt("editionNumber")); + book.setCopyright(results.getString("copyright")); + book.setPublisherId(results.getInt("publisherID")); + book.setImageFile(results.getString("imageFile")); + book.setPrice(results.getFloat("price")); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + return book; + } + +} \ No newline at end of file diff --git a/Example_src/Chapter1-10/src/ch10/TitleDaoImplTest.java b/Example_src/Chapter1-10/src/ch10/TitleDaoImplTest.java new file mode 100644 index 0000000..36f682d --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/TitleDaoImplTest.java @@ -0,0 +1,37 @@ +package ch10; + + +import java.util.List; + +import org.junit.jupiter.api.Test; + + +class TitleDaoImplTest { + + //@Test + void testAddTitle() { + + } + + @Test + void testGetByTitle() { + List list = null; + TitleDaoImpl dao = new TitleDaoImpl(); + list = dao.getByTitle("java"); + Titles title = null; + for (int i = 0; i < list.size(); i++) { + title = (Titles) list.get(i); + System.out.println(title.getTitle()); + } + } + + //@Test + void testGetByIsbn() { + TitleDaoImpl dao = new TitleDaoImpl(); + Titles title = null; + title = dao.getByIsbn("01234566771"); + if (title != null) System.out.println(title.getIsbn()); + else System.out.println("error"); + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/Titles.java b/Example_src/Chapter1-10/src/ch10/Titles.java new file mode 100644 index 0000000..ae163a8 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/Titles.java @@ -0,0 +1,77 @@ +package ch10; + +public class Titles { + private String isbn; //Isbn号 + private String title; //书名 + private String copyright; //版权 + private String imageFile; //封面图像文件名称 + private int editionNumber; //版本号 + private int publisherId; //出版商ID + private float price; //价格 + private String summary; + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getCopyright() { + return copyright; + } + + public void setCopyright(String copyright) { + this.copyright = copyright; + } + + public String getImageFile() { + return imageFile; + } + + public void setImageFile(String imageFile) { + this.imageFile = imageFile; + } + + public int getEditionNumber() { + return editionNumber; + } + + public void setEditionNumber(int editionNumber) { + this.editionNumber = editionNumber; + } + + public int getPublisherId() { + return publisherId; + } + + public void setPublisherId(int publisherId) { + this.publisherId = publisherId; + } + + public float getPrice() { + return price; + } + + public void setPrice(float price) { + this.price = price; + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/UserInfo.java b/Example_src/Chapter1-10/src/ch10/UserInfo.java new file mode 100644 index 0000000..607a226 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/UserInfo.java @@ -0,0 +1,32 @@ +package ch10; + +public class UserInfo { + private int userId; + private String loginName; + private String password; + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/UserinfoDao.java b/Example_src/Chapter1-10/src/ch10/UserinfoDao.java new file mode 100644 index 0000000..d158d0c --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/UserinfoDao.java @@ -0,0 +1,90 @@ +package ch10; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class UserinfoDao { + private Connection con; + private PreparedStatement pstmt; + private ResultSet results; + + public int addUserinfo(UserInfo userinfo) { + int result = 0; + con = ConnectionManager.getConnction(); + try { + String sql = "insert into userinfo(loginname,password) values(?,?)"; + pstmt = con.prepareStatement(sql); + pstmt.setString(1, userinfo.getLoginName()); + pstmt.setString(2, userinfo.getPassword()); + result = pstmt.executeUpdate(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeResultSet(results); + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + public int delUserinfo(int id) { + int result = 0; + con = ConnectionManager.getConnction(); + try { + String sql = "delete from userinfo where userid=? "; + pstmt = con.prepareStatement(sql); + pstmt.setInt(1, id); + + result = pstmt.executeUpdate(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeResultSet(results); + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + public int updateUserinfo(UserInfo userinfo) { + int result = 0; + con = ConnectionManager.getConnction(); + try { + String sql = "update userinfo set loginname=?,password=? where userid=?"; + pstmt = con.prepareStatement(sql); + pstmt.setString(1, userinfo.getLoginName()); + pstmt.setString(2, userinfo.getPassword()); + pstmt.setInt(3, userinfo.getUserId()); + result = pstmt.executeUpdate(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + ConnectionManager.closeResultSet(results); + ConnectionManager.closeStatement(pstmt);//释放PreparedStatement对象 + ConnectionManager.closeConnection(con);//关闭与数据库连接 + } + return result; + } + + public UserInfo findByLoginname(String loginname) { + UserInfo user = new UserInfo(); + String sql = "select * from userinfo where loginname=? "; + con = ConnectionManager.getConnction(); + try { + pstmt = con.prepareStatement(sql); + pstmt.setString(1, loginname); + results = pstmt.executeQuery(); + if (results.next()) { + user.setLoginName(results.getString("loginname")); + user.setPassword(results.getString("password")); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return user; + } +} diff --git a/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest.java b/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest.java new file mode 100644 index 0000000..41860dc --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest.java @@ -0,0 +1,19 @@ +package ch10; + +public class UserinfoDaoTest { + + public static void main(String[] args) { + UserinfoDao dao = new UserinfoDao(); + UserInfo user = new UserInfo(); + user.setLoginName("lili"); + user.setPassword("123456"); + //int n=dao.addUserinfo(user); + //int n=dao.delUserinfo(6); + user = dao.findByLoginname("admin"); + if (user != null) + System.out.println(user.getPassword()); + + + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest1.java b/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest1.java new file mode 100644 index 0000000..26abd7a --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/UserinfoDaoTest1.java @@ -0,0 +1,45 @@ +package ch10; + +import org.junit.jupiter.api.Test; + +class UserinfoDaoTest1 { + + @Test + void testAddUserinfo() { + UserinfoDao dao = new UserinfoDao(); + UserInfo user = new UserInfo(); + user.setLoginName("admin3"); + user.setPassword("222222"); + + int n = dao.addUserinfo(user); + if (n > 0) System.out.println("ok"); + else System.out.println("error"); + } + + @Test + void testDelUserinfo() { + UserinfoDao dao = new UserinfoDao(); + int n = dao.delUserinfo(5); + if (n > 0) System.out.println("ok"); + else System.out.println("error"); + } + + //@Test + void testUpdateUserinfo() { + + } + + @Test + void testFindByLoginname() { + UserinfoDao dao = new UserinfoDao(); + UserInfo user = new UserInfo(); + user.setLoginName("lili"); + user.setPassword("123456"); + //int n=dao.addUserinfo(user); + //int n=dao.delUserinfo(6); + user = dao.findByLoginname("admin"); + if (user != null) + System.out.println(user.getPassword()); + } + +} diff --git a/Example_src/Chapter1-10/src/ch10/userinfo.sql b/Example_src/Chapter1-10/src/ch10/userinfo.sql new file mode 100644 index 0000000..3e30322 --- /dev/null +++ b/Example_src/Chapter1-10/src/ch10/userinfo.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS `userinfo`; +CREATE TABLE `userinfo` +( + `userId` int(11) NOT NULL auto_increment, + `loginname` varchar(20) default NULL, + `password` varchar(10) default NULL, + PRIMARY KEY (`userId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `userinfo` (`userId`, `loginname`, `password`) +VALUES (1, 'admin', 'admin'); \ No newline at end of file diff --git a/Exercise/.gitignore b/Exercise/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/Exercise/.gitignore @@ -0,0 +1,29 @@ +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/Exercise/.idea/.gitignore b/Exercise/.idea/.gitignore new file mode 100644 index 0000000..7d05e99 --- /dev/null +++ b/Exercise/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# 依赖于环境的 Maven 主目录路径 +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/Exercise/.idea/misc.xml b/Exercise/.idea/misc.xml new file mode 100644 index 0000000..6f29fee --- /dev/null +++ b/Exercise/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Exercise/.idea/modules.xml b/Exercise/.idea/modules.xml new file mode 100644 index 0000000..52fb23e --- /dev/null +++ b/Exercise/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Exercise/.idea/uiDesigner.xml b/Exercise/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/Exercise/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Exercise/.idea/vcs.xml b/Exercise/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/Exercise/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Exercise/Exercise.iml b/Exercise/Exercise.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/Exercise/Exercise.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Exercise/src/Chapter3/AverageScore.java b/Exercise/src/Chapter3/AverageScore.java new file mode 100644 index 0000000..764dda6 --- /dev/null +++ b/Exercise/src/Chapter3/AverageScore.java @@ -0,0 +1,19 @@ +package Chapter3; + +import java.util.Scanner; + +public class AverageScore { + public static void main(String[] args) { + final int NUMBER_OF_MEMBERS = 5; + double totalScore = 0; + Scanner scanner = new Scanner(System.in); + System.out.println("请输入 " + NUMBER_OF_MEMBERS + " 位小组成员的分数:"); + for (int i = 1; i <= NUMBER_OF_MEMBERS; i++) { + System.out.print("请输入第 " + i + " 位成员的分数: "); + totalScore += scanner.nextDouble(); + } + double averageScore = totalScore / NUMBER_OF_MEMBERS; + System.out.println("小组的平均分数为: " + averageScore); + scanner.close(); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter3/BmiCalc.java b/Exercise/src/Chapter3/BmiCalc.java new file mode 100644 index 0000000..1f56aba --- /dev/null +++ b/Exercise/src/Chapter3/BmiCalc.java @@ -0,0 +1,17 @@ +package Chapter3; + +import java.util.Scanner; + +public class BmiCalc { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("输入身高单位为m:"); + double heightM = scanner.nextDouble(); + System.out.println("输入体重单位为kg:"); + double weightKg = scanner.nextDouble(); + double bmiValue = weightKg / (heightM * heightM); + int bmiInteger = (int) bmiValue; + System.out.println("得出的BMI的值为: " + bmiInteger); + scanner.close(); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter3/KfcSales.java b/Exercise/src/Chapter3/KfcSales.java new file mode 100644 index 0000000..029df12 --- /dev/null +++ b/Exercise/src/Chapter3/KfcSales.java @@ -0,0 +1,16 @@ +package Chapter3; + +import java.util.Scanner; + +public class KfcSales { + public static void main(String[] args) { + final double PRICE_PER_HAMBURGER = 15.5; + Scanner scanner = new Scanner(System.in); + System.out.println("请输入售出汉堡的数量:"); + int numberOfHamburgers = scanner.nextInt(); + double totalSales = numberOfHamburgers * PRICE_PER_HAMBURGER; + System.out.println("一天总出售的汉堡数量为: " + numberOfHamburgers + "个"); + System.out.printf("全天售出的总金额为: %.1f元\n", totalSales); + scanner.close(); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter3/PaymentResult.java b/Exercise/src/Chapter3/PaymentResult.java new file mode 100644 index 0000000..8a7a929 --- /dev/null +++ b/Exercise/src/Chapter3/PaymentResult.java @@ -0,0 +1,21 @@ +package Chapter3; + +import java.util.Scanner; + +public class PaymentResult { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("请输入支付金额:"); + double paymentAmount = scanner.nextDouble(); + System.out.println("\n支付成功"); + System.out.println("京东商城"); + System.out.printf("%.1f元\n", paymentAmount); + System.out.println("优惠金额\t\t10.00元"); + System.out.println("支付方式\t\t工商银行储蓄卡(5009)"); + System.out.println("交易时间\t\t2018-11-27 00:34:02"); + System.out.println("订单编号\t\t893412929"); + + scanner.close(); + } + +} diff --git a/Exercise/src/Chapter3/ProteinInMilk.java b/Exercise/src/Chapter3/ProteinInMilk.java new file mode 100644 index 0000000..8e1c2e8 --- /dev/null +++ b/Exercise/src/Chapter3/ProteinInMilk.java @@ -0,0 +1,15 @@ +package Chapter3; + +import java.util.Scanner; + +public class ProteinInMilk { + public static void main(String[] args) { + final double PROTEIN_PER_CARTON = 6.4; + Scanner scanner = new Scanner(System.in); + System.out.println("请输入购买牛奶的盒数:"); + int numberOfCartons = scanner.nextInt(); + double totalProtein = numberOfCartons * PROTEIN_PER_CARTON; + System.out.println(numberOfCartons + "袋牛奶含有的蛋白质: " + totalProtein + "g"); + scanner.close(); + } +} diff --git a/Exercise/src/Chapter3/SpeedConvert.java b/Exercise/src/Chapter3/SpeedConvert.java new file mode 100644 index 0000000..dccb454 --- /dev/null +++ b/Exercise/src/Chapter3/SpeedConvert.java @@ -0,0 +1,15 @@ +package Chapter3; + +import java.util.Scanner; + +public class SpeedConvert { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("请输入速度:"); + double speedKmh = scanner.nextDouble(); + double speedMsRaw = speedKmh / 3.6; + double speedMsFormatted = Math.floor(speedMsRaw); + System.out.printf("%.0fkm/h = %.1fm/s\n", speedKmh, speedMsFormatted); + scanner.close(); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter3/SubwayTicket.java b/Exercise/src/Chapter3/SubwayTicket.java new file mode 100644 index 0000000..101788b --- /dev/null +++ b/Exercise/src/Chapter3/SubwayTicket.java @@ -0,0 +1,24 @@ +package Chapter3; + +import java.util.Scanner; + +public class SubwayTicket { + public static void main(String[] args) { + final String DESTINATION = "人民广场"; + final double TICKET_PRICE = 2.00; + Scanner scanner = new Scanner(System.in); + System.out.println("购票信息"); + System.out.println("--------------------"); + System.out.println("目的车站: " + DESTINATION); + System.out.printf("票价: %.2f\n", TICKET_PRICE); + System.out.print("购票数量: "); + int numberOfTickets = scanner.nextInt(); + double amountDue = numberOfTickets * TICKET_PRICE; + System.out.printf("应付金额: %.0f\n", amountDue); + System.out.print("已付金额: "); + int amountPaid = scanner.nextInt(); + double change = amountPaid - amountDue; + System.out.printf("找零: %.0f\n", change); + scanner.close(); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter3/TruckCapacity.java b/Exercise/src/Chapter3/TruckCapacity.java new file mode 100644 index 0000000..d8d6bb1 --- /dev/null +++ b/Exercise/src/Chapter3/TruckCapacity.java @@ -0,0 +1,17 @@ +package Chapter3; + +public class TruckCapacity { + public static void main(String[] args) { + double truckLength = 4.2; + double truckWidth = 1.9; + double truckHeight = 1.9; + double boxLength = 0.5; + double boxWidth = 0.5; + double boxHeight = 0.3; + int boxesAlongLength = (int) (truckLength / boxLength); + int boxesAlongWidth = (int) (truckWidth / boxWidth); + int boxesAlongHeight = (int) (truckHeight / boxHeight); + int totalBoxes = boxesAlongLength * boxesAlongWidth * boxesAlongHeight; + System.out.println("德邦物流车可以装载 " + totalBoxes + " 个这样规格的箱子。"); + } +} \ No newline at end of file diff --git a/Exercise/src/Chapter4/FilterApartment.java b/Exercise/src/Chapter4/FilterApartment.java new file mode 100644 index 0000000..996c1b7 --- /dev/null +++ b/Exercise/src/Chapter4/FilterApartment.java @@ -0,0 +1,17 @@ +package Chapter4; + +public class FilterApartment { + public static void main(String[] args) { + int area, level, price; + java.util.Scanner scanner = new java.util.Scanner(System.in); + System.out.println("请输入您要购买的楼房的面积:"); + area = scanner.nextInt(); + System.out.println("以上购房面积符合您的要求"); + System.out.println("请输入您的楼层数:"); + level = scanner.nextInt(); + System.out.println("以上的楼层数符合您的要求"); + System.out.println("请输入您能承担总价格:"); + price = scanner.nextInt(); + System.out.println("以上楼房总价格在您的承受范围内"); + } +} diff --git a/Exercise/src/Chapter4/PayElectricityBill.java b/Exercise/src/Chapter4/PayElectricityBill.java new file mode 100644 index 0000000..393400c --- /dev/null +++ b/Exercise/src/Chapter4/PayElectricityBill.java @@ -0,0 +1,24 @@ +package Chapter4; + +public class PayElectricityBill { + public static void main (String[] args) { + final int ARREARS_AMOUNT = 574; + System.out.println("欠费金额: " + ARREARS_AMOUNT + "元"); + System.out.println("户名:长春惠鹏石油化工科技有限公司"); + System.out.println("户号:0140117369"); + System.out.println("地址:吉林省长春市二道区中意之尊小区4#楼商铺101"); + System.out.println("截止时间:19日4时"); + java.util.Scanner scanner = new java.util.Scanner(System.in); + while (true) { + System.out.println("请输入缴费金额(大于574):"); + int pay_amount = scanner.nextInt(); + if (pay_amount < ARREARS_AMOUNT) { + System.out.println("缴费金额不足,请重新输入!"); + } else { + int balance = pay_amount - ARREARS_AMOUNT; + System.out.println("账户电费余额为:" + balance); + break; + } + } + } +} diff --git a/Experiment/.gitignore b/Experiment/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/Experiment/.gitignore @@ -0,0 +1,29 @@ +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/Experiment/.idea/.gitignore b/Experiment/.idea/.gitignore new file mode 100644 index 0000000..7d05e99 --- /dev/null +++ b/Experiment/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# 依赖于环境的 Maven 主目录路径 +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/Experiment/.idea/misc.xml b/Experiment/.idea/misc.xml new file mode 100644 index 0000000..5af9c98 --- /dev/null +++ b/Experiment/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Experiment/.idea/modules.xml b/Experiment/.idea/modules.xml new file mode 100644 index 0000000..885cffb --- /dev/null +++ b/Experiment/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/AbFather_Main.xml b/Experiment/.idea/runConfigurations/AbFather_Main.xml new file mode 100644 index 0000000..fae13e2 --- /dev/null +++ b/Experiment/.idea/runConfigurations/AbFather_Main.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/ArithmaticOp.xml b/Experiment/.idea/runConfigurations/ArithmaticOp.xml new file mode 100644 index 0000000..af47b40 --- /dev/null +++ b/Experiment/.idea/runConfigurations/ArithmaticOp.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/ArrayRefer.xml b/Experiment/.idea/runConfigurations/ArrayRefer.xml new file mode 100644 index 0000000..0db14b3 --- /dev/null +++ b/Experiment/.idea/runConfigurations/ArrayRefer.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/BackAnimal.xml b/Experiment/.idea/runConfigurations/BackAnimal.xml new file mode 100644 index 0000000..df669b4 --- /dev/null +++ b/Experiment/.idea/runConfigurations/BackAnimal.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Ball_Class1.xml b/Experiment/.idea/runConfigurations/Ball_Class1.xml new file mode 100644 index 0000000..7d58454 --- /dev/null +++ b/Experiment/.idea/runConfigurations/Ball_Class1.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/CircleCalc.xml b/Experiment/.idea/runConfigurations/CircleCalc.xml new file mode 100644 index 0000000..a051f6c --- /dev/null +++ b/Experiment/.idea/runConfigurations/CircleCalc.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/CircleTest.xml b/Experiment/.idea/runConfigurations/CircleTest.xml new file mode 100644 index 0000000..6bc409e --- /dev/null +++ b/Experiment/.idea/runConfigurations/CircleTest.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/CircularFactorial.xml b/Experiment/.idea/runConfigurations/CircularFactorial.xml new file mode 100644 index 0000000..4272570 --- /dev/null +++ b/Experiment/.idea/runConfigurations/CircularFactorial.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/CollectionStringProcessing.xml b/Experiment/.idea/runConfigurations/CollectionStringProcessing.xml new file mode 100644 index 0000000..b211b58 --- /dev/null +++ b/Experiment/.idea/runConfigurations/CollectionStringProcessing.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/DivideByZero.xml b/Experiment/.idea/runConfigurations/DivideByZero.xml new file mode 100644 index 0000000..ca56206 --- /dev/null +++ b/Experiment/.idea/runConfigurations/DivideByZero.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/FibonacciSeq.xml b/Experiment/.idea/runConfigurations/FibonacciSeq.xml new file mode 100644 index 0000000..dae6dfe --- /dev/null +++ b/Experiment/.idea/runConfigurations/FibonacciSeq.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/FibonacciSum.xml b/Experiment/.idea/runConfigurations/FibonacciSum.xml new file mode 100644 index 0000000..760ca7a --- /dev/null +++ b/Experiment/.idea/runConfigurations/FibonacciSum.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/FileContentCopy.xml b/Experiment/.idea/runConfigurations/FileContentCopy.xml new file mode 100644 index 0000000..003bc3c --- /dev/null +++ b/Experiment/.idea/runConfigurations/FileContentCopy.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Graphic_Test.xml b/Experiment/.idea/runConfigurations/Graphic_Test.xml new file mode 100644 index 0000000..85a7c29 --- /dev/null +++ b/Experiment/.idea/runConfigurations/Graphic_Test.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/GuessNumber_Start.xml b/Experiment/.idea/runConfigurations/GuessNumber_Start.xml new file mode 100644 index 0000000..d519ca5 --- /dev/null +++ b/Experiment/.idea/runConfigurations/GuessNumber_Start.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/HelloWorld.xml b/Experiment/.idea/runConfigurations/HelloWorld.xml new file mode 100644 index 0000000..9f9d475 --- /dev/null +++ b/Experiment/.idea/runConfigurations/HelloWorld.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/ManyException.xml b/Experiment/.idea/runConfigurations/ManyException.xml new file mode 100644 index 0000000..63e0ad8 --- /dev/null +++ b/Experiment/.idea/runConfigurations/ManyException.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Max.xml b/Experiment/.idea/runConfigurations/Max.xml new file mode 100644 index 0000000..a227827 --- /dev/null +++ b/Experiment/.idea/runConfigurations/Max.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/MaxArray_Test.xml b/Experiment/.idea/runConfigurations/MaxArray_Test.xml new file mode 100644 index 0000000..4bcf68c --- /dev/null +++ b/Experiment/.idea/runConfigurations/MaxArray_Test.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/PersonTest.xml b/Experiment/.idea/runConfigurations/PersonTest.xml new file mode 100644 index 0000000..3b72913 --- /dev/null +++ b/Experiment/.idea/runConfigurations/PersonTest.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Person_Test.xml b/Experiment/.idea/runConfigurations/Person_Test.xml new file mode 100644 index 0000000..2f7c84b --- /dev/null +++ b/Experiment/.idea/runConfigurations/Person_Test.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/PrimeNum.xml b/Experiment/.idea/runConfigurations/PrimeNum.xml new file mode 100644 index 0000000..3ad1e97 --- /dev/null +++ b/Experiment/.idea/runConfigurations/PrimeNum.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/PythagoreanTheorem.xml b/Experiment/.idea/runConfigurations/PythagoreanTheorem.xml new file mode 100644 index 0000000..9c760e5 --- /dev/null +++ b/Experiment/.idea/runConfigurations/PythagoreanTheorem.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/RRect_Class1.xml b/Experiment/.idea/runConfigurations/RRect_Class1.xml new file mode 100644 index 0000000..b49fa23 --- /dev/null +++ b/Experiment/.idea/runConfigurations/RRect_Class1.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Rectangle_Test1.xml b/Experiment/.idea/runConfigurations/Rectangle_Test1.xml new file mode 100644 index 0000000..3174620 --- /dev/null +++ b/Experiment/.idea/runConfigurations/Rectangle_Test1.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/RecursiveFactorial.xml b/Experiment/.idea/runConfigurations/RecursiveFactorial.xml new file mode 100644 index 0000000..754ed82 --- /dev/null +++ b/Experiment/.idea/runConfigurations/RecursiveFactorial.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/SafeTriangle.xml b/Experiment/.idea/runConfigurations/SafeTriangle.xml new file mode 100644 index 0000000..20e1210 --- /dev/null +++ b/Experiment/.idea/runConfigurations/SafeTriangle.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/Say.xml b/Experiment/.idea/runConfigurations/Say.xml new file mode 100644 index 0000000..f2ce7dd --- /dev/null +++ b/Experiment/.idea/runConfigurations/Say.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/SimpleTypes.xml b/Experiment/.idea/runConfigurations/SimpleTypes.xml new file mode 100644 index 0000000..3dff0ea --- /dev/null +++ b/Experiment/.idea/runConfigurations/SimpleTypes.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/SortNum.xml b/Experiment/.idea/runConfigurations/SortNum.xml new file mode 100644 index 0000000..b3ffb02 --- /dev/null +++ b/Experiment/.idea/runConfigurations/SortNum.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/StringManipulation.xml b/Experiment/.idea/runConfigurations/StringManipulation.xml new file mode 100644 index 0000000..2d8318c --- /dev/null +++ b/Experiment/.idea/runConfigurations/StringManipulation.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/StringReplacement.xml b/Experiment/.idea/runConfigurations/StringReplacement.xml new file mode 100644 index 0000000..b2694b3 --- /dev/null +++ b/Experiment/.idea/runConfigurations/StringReplacement.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/TestMyDateTools.xml b/Experiment/.idea/runConfigurations/TestMyDateTools.xml new file mode 100644 index 0000000..d3d45e7 --- /dev/null +++ b/Experiment/.idea/runConfigurations/TestMyDateTools.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/TransCard.xml b/Experiment/.idea/runConfigurations/TransCard.xml new file mode 100644 index 0000000..ed343c3 --- /dev/null +++ b/Experiment/.idea/runConfigurations/TransCard.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/runConfigurations/U2.xml b/Experiment/.idea/runConfigurations/U2.xml new file mode 100644 index 0000000..654788c --- /dev/null +++ b/Experiment/.idea/runConfigurations/U2.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Experiment/.idea/uiDesigner.xml b/Experiment/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/Experiment/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Experiment/.idea/vcs.xml b/Experiment/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/Experiment/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Experiment/Experiment.iml b/Experiment/Experiment.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/Experiment/Experiment.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Experiment/graph/Exp1/ArithmaticOp.mermaid b/Experiment/graph/Exp1/ArithmaticOp.mermaid new file mode 100644 index 0000000..043bac9 --- /dev/null +++ b/Experiment/graph/Exp1/ArithmaticOp.mermaid @@ -0,0 +1,14 @@ +flowchart TD + A[开始] --> B[计算 a = 5 + 4] + B --> C[计算 b = a * 2] + C --> D[计算 c = b / 4] + D --> E[计算 d = b - c] + E --> F[计算 e = -d] + F --> G[计算 f = e % 4] + G --> H[定义 g = 18.4] + H --> I[计算 h = g % 4] + I --> J[定义 i = 3] + J --> K[计算 j = i++] + K --> L[计算 k = ++i] + L --> M[输出所有变量的值] + M --> N[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp1/ArrayRefer.mermaid b/Experiment/graph/Exp1/ArrayRefer.mermaid new file mode 100644 index 0000000..ef6736e --- /dev/null +++ b/Experiment/graph/Exp1/ArrayRefer.mermaid @@ -0,0 +1,14 @@ +flowchart TD + A[开始] --> B[定义变量 i] + B --> C[创建大小为5的整型数组 arrayA] + C --> D[初始化循环 i = 0] + D --> E{i < 5?} + E -->|是| F["arrayA[i] = i"] + F --> G[i++] + G --> E + E -->|否| H[重置循环 i = 0] + H --> I{i < arrayA.length?} + I -->|是| J["输出 arrayA[i] 的值"] + J --> K[i++] + K --> I + I -->|否| L[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp1/CircleCalc.mermaid b/Experiment/graph/Exp1/CircleCalc.mermaid new file mode 100644 index 0000000..d190f82 --- /dev/null +++ b/Experiment/graph/Exp1/CircleCalc.mermaid @@ -0,0 +1,7 @@ +flowchart TD + A[开始] --> B[定义半径 radius = 3.0] + B --> C[计算周长 circumference = 2 * Math.PI * radius] + C --> D[计算面积 area = Math.PI * radius * radius] + D --> E[输出圆的周长] + E --> F[输出圆的面积] + F --> G[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp1/Max.mermaid b/Experiment/graph/Exp1/Max.mermaid new file mode 100644 index 0000000..0b8ba87 --- /dev/null +++ b/Experiment/graph/Exp1/Max.mermaid @@ -0,0 +1,12 @@ +flowchart TD + A[开始] --> B[定义变量 max] + B --> C[从命令行参数获取 a, b, c] + C --> D{a > b 且 a > c?} + D -->|是| E[max = a] + D -->|否| F{b > c?} + F -->|是| G[max = b] + F -->|否| H[max = c] + E --> I[输出最大值] + G --> I + H --> I + I --> J[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp1/PythagoreanTheorem.mermaid b/Experiment/graph/Exp1/PythagoreanTheorem.mermaid new file mode 100644 index 0000000..328bab3 --- /dev/null +++ b/Experiment/graph/Exp1/PythagoreanTheorem.mermaid @@ -0,0 +1,9 @@ +flowchart TD + A[开始] --> B[输出提示信息: 请输入直角三角形的两条直角边的长度] + B --> C[创建Scanner对象] + C --> D[读取第一个数值 a] + D --> E[读取第二个数值 b] + E --> F[关闭Scanner对象] + F --> G["计算斜边长度 $$c = \sqrt{a² + b²}$$"] + G --> H[输出斜边长度] + H --> I[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp1/Say.mermaid b/Experiment/graph/Exp1/Say.mermaid new file mode 100644 index 0000000..1fd64e8 --- /dev/null +++ b/Experiment/graph/Exp1/Say.mermaid @@ -0,0 +1,8 @@ +flowchart TD + A[开始] --> B{命令行参数数量 < 2?} + B -->|是| C[输出错误信息] + C --> D[退出程序] + B -->|否| E[获取参数 name 和 word] + E --> F[输出格式化消息] + F --> G[结束] + D --> G \ No newline at end of file diff --git a/Experiment/graph/Exp1/SimpleTypes.mermaid b/Experiment/graph/Exp1/SimpleTypes.mermaid new file mode 100644 index 0000000..557904a --- /dev/null +++ b/Experiment/graph/Exp1/SimpleTypes.mermaid @@ -0,0 +1,11 @@ +flowchart TD + A[开始] --> B[定义 byte b = 055] + B --> C[定义 short s = 0x55FF] + C --> D[定义 int i = 1000000] + D --> E[定义 long l = 3615L] + E --> F[定义 char c = 'c'] + F --> G[定义 float f = 0.23F] + G --> H[定义 double d = 0.7E-3] + H --> I[定义 boolean bool = true] + I --> J[输出所有变量的值] + J --> K[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp2/CircularFactorial.mermaid b/Experiment/graph/Exp2/CircularFactorial.mermaid new file mode 100644 index 0000000..95dd056 --- /dev/null +++ b/Experiment/graph/Exp2/CircularFactorial.mermaid @@ -0,0 +1,12 @@ +flowchart TD + A[开始] --> B[定义 n = 10] + B --> C[初始化 result = 1] + C --> D{n == 0 或 n == 1?} + D -- 是 --> E[result = 1] + D -- 否 --> F[循环: i = 2 到 n] + F --> G[result *= i] + G --> H{i < n?} + H -- 是 --> F + H -- 否 --> I[输出 n! = result] + E --> I + I --> J[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp2/PrimeNum.mermaid b/Experiment/graph/Exp2/PrimeNum.mermaid new file mode 100644 index 0000000..6eaaabe --- /dev/null +++ b/Experiment/graph/Exp2/PrimeNum.mermaid @@ -0,0 +1,26 @@ +flowchart TD + A[开始] --> B[定义 start = 100, end = 2000] + B --> C[初始化 num_in_line = 0] + C --> D["输出 100~2000之间的素数有:"] + D --> E[循环: i = start 到 end] + E --> F{"isPrime(i)?"} + F -- 是 --> G[num_in_line++] + G --> H{num_in_line % 5 == 0?} + H -- 是 --> I[输出 i 并换行] + H -- 否 --> J[输出 i 和空格] + I --> K{i < end?} + J --> K + K -- 是 --> E + K -- 否 --> L[结束] + F -- 否 --> K + + subgraph isPrime函数 + M["isPrime(n)"] --> N{n <= 1?} + N -- 是 --> O[返回 false] + N -- 否 --> P["循环: i = 2 到 sqrt(n)"] + P --> Q{n % i == 0?} + Q -- 是 --> R[返回 false] + Q -- 否 --> S{"i < sqrt(n)?"} + S -- 是 --> P + S -- 否 --> T[返回 true] + end \ No newline at end of file diff --git a/Experiment/graph/Exp2/RecursiveFactorial.mermaid b/Experiment/graph/Exp2/RecursiveFactorial.mermaid new file mode 100644 index 0000000..1e2cb49 --- /dev/null +++ b/Experiment/graph/Exp2/RecursiveFactorial.mermaid @@ -0,0 +1,12 @@ +flowchart TD + A[开始] --> B[定义 n = 10] + B --> C["调用 factorial(n)"] + C --> D[输出 n! = result] + D --> E[结束] + + subgraph factorial函数 + F["factorial(n)"] --> G{n == 0 或 n == 1?} + G -- 是 --> H[返回 1] + G -- 否 --> I["返回 n * factorial(n-1)"] + I -- "递归调用 factorial(n-1)" --> F + end \ No newline at end of file diff --git a/Experiment/graph/Exp2/SortNum.mermaid b/Experiment/graph/Exp2/SortNum.mermaid new file mode 100644 index 0000000..0039488 --- /dev/null +++ b/Experiment/graph/Exp2/SortNum.mermaid @@ -0,0 +1,16 @@ +flowchart TD + A[开始] --> B[定义 a=9, b=5, c=7, t] + B --> C{a > b?} + C -->|是| D[t=a, a=b, b=t] + C -->|否| E[继续] + D --> E + E --> F{a > c?} + F -->|是| G[t=a, a=c, c=t] + F -->|否| H[继续] + G --> H + H --> I{b > c?} + I -->|是| J[t=b, b=c, c=t] + I -->|否| K[继续] + J --> K + K --> L[输出 a, b, c的值] + L --> M[结束] \ No newline at end of file diff --git a/Experiment/graph/Exp2/U2.mermaid b/Experiment/graph/Exp2/U2.mermaid new file mode 100644 index 0000000..a84e681 --- /dev/null +++ b/Experiment/graph/Exp2/U2.mermaid @@ -0,0 +1,18 @@ +flowchart TD + A[开始] --> B[定义 score = 55] + B --> C["switch(score / 10)"] + C --> D{case 0,1,2,3,4,5} + D -- 匹配 --> E[输出 score 分是D等] + C --> F{case 6} + F -- 匹配 --> G[输出 score 分是C等] + C --> H{case 7,8} + H -- 匹配 --> I[输出 score 分是B等] + C --> J{case 9,10} + J -- 匹配 --> K[输出 score 分是A等] + C --> L{default} + L -- 匹配 --> M[输出 数据错误] + E --> N[结束] + G --> N + I --> N + K --> N + M --> N \ No newline at end of file diff --git a/Experiment/graph/Exp3/Circle.mermaid b/Experiment/graph/Exp3/Circle.mermaid new file mode 100644 index 0000000..5fa1921 --- /dev/null +++ b/Experiment/graph/Exp3/Circle.mermaid @@ -0,0 +1,10 @@ +flowchart TD + Start([开始]) --> A[创建Circle对象c,半径为5] + A --> B1[Circle构造函数执行] + B1 --> B2[设置radius=5] + B2 --> B3[计算周长$$perimeter=2\times π\times radius$$] + B3 --> B4[计算面积$$area=π\times radius\times radius$$] + B4 --> C["调用c.getRadius()打印半径"] + C --> D["调用c.getPerimeter()打印周长"] + D --> E["调用c.getArea()打印面积"] + E --> End([结束]) \ No newline at end of file diff --git a/Experiment/graph/Exp3/Person.mermaid b/Experiment/graph/Exp3/Person.mermaid new file mode 100644 index 0000000..f065a44 --- /dev/null +++ b/Experiment/graph/Exp3/Person.mermaid @@ -0,0 +1,11 @@ +flowchart TD + Start([开始]) --> A[创建Person对象p] + A --> B[调用p.addPerson方法] + B --> B1[设置IdPerson=123] + B1 --> B2["设置Name='John Doe'"] + B2 --> B3[设置Sex='M'] + B3 --> B4[设置Birthday=1990-01-01] + B4 --> B5["设置HomeAddress='123 Main St'"] + B5 --> C[调用p.showPerson方法] + C --> C1[打印IdPerson, Name, Sex, Birthday, HomeAddress] + C1 --> End([结束]) \ No newline at end of file diff --git a/Experiment/graph/Exp3/Rectangle.mermaid b/Experiment/graph/Exp3/Rectangle.mermaid new file mode 100644 index 0000000..3e464d5 --- /dev/null +++ b/Experiment/graph/Exp3/Rectangle.mermaid @@ -0,0 +1,16 @@ +flowchart TD + Start([开始]) --> A["创建Rectangle对象rect1(5,3)"] + A --> A1[设置lx=0, ly=0] + A1 --> A2[设置rx=5, ry=3] + A2 --> B[打印rect1周长] + B --> B1["计算周长:$$2\times(|rx-lx|+|ry-ly|)$$"] + B1 --> C[打印rect1面积] + C --> C1["计算面积:$$|rx-lx|\times|ry-ly|$$"] + C1 --> D["创建Rectangle对象rect2(1,6,6,2)"] + D --> D1[设置lx=1, ly=6] + D1 --> D2[设置rx=6, ry=2] + D2 --> E[打印rect2周长] + E --> E1["计算周长:$$2\times(|rx-lx|+|ry-ly|)$$"] + E1 --> F[打印rect2面积] + F --> F1["计算面积:$$|rx-lx|\times|ry-ly|$$"] + F1 --> End([结束]) \ No newline at end of file diff --git a/Experiment/graph/Exp4/AbFather.mermaid b/Experiment/graph/Exp4/AbFather.mermaid new file mode 100644 index 0000000..0b3fd6b --- /dev/null +++ b/Experiment/graph/Exp4/AbFather.mermaid @@ -0,0 +1,27 @@ +classDiagram + class Father { + <> + # double height + # double weight + + Father(double height, double weight) + + double getHeight() + + void setHeight(double height) + + double getWeight() + + void setWeight(double weight) + + void hobby() + } + + class Son { + - String personality + + Son(double height, double weight, String personality) + + String getPersonality() + + void setPersonality(String personality) + + void hobby() + } + + class Main { + + main(String[] args) + } + + Father <|-- Son : 继承 + Main --> Son : 创建与使用 \ No newline at end of file diff --git a/Experiment/graph/Exp4/Graphic.mermaid b/Experiment/graph/Exp4/Graphic.mermaid new file mode 100644 index 0000000..9dfa842 --- /dev/null +++ b/Experiment/graph/Exp4/Graphic.mermaid @@ -0,0 +1,33 @@ +classDiagram + class Graphic { + <> + + double area() + + double perimeter() + } + + class Circle { + - double radius + + Circle(double radius) + + double area() + + double perimeter() + + double getRadius() + } + + class Rectangle { + - double width + - double height + + Rectangle(double width, double height) + + double area() + + double perimeter() + + double getWidth() + + double getHeight() + } + + class Test { + + main(String[] args) + } + + Graphic <|.. Circle : 实现 + Graphic <|.. Rectangle : 实现 + Test --> Circle : 创建与使用 + Test --> Rectangle : 创建与使用 \ No newline at end of file diff --git a/Experiment/graph/Exp4/RRect.mermaid b/Experiment/graph/Exp4/RRect.mermaid new file mode 100644 index 0000000..94917b9 --- /dev/null +++ b/Experiment/graph/Exp4/RRect.mermaid @@ -0,0 +1,26 @@ +classDiagram + class calrect { + <> + + int calarea() + + int calgirth() + + int getx() + + int gety() + } + + class RRect { + - int x + - int y + + RRect() + + int calarea() + + int calgirth() + + int getx() + + int gety() + } + + class Class1 { + + RRect rect + + main(String[] args) + } + + calrect <|.. RRect : 实现 + Class1 --> RRect : 创建与使用 \ No newline at end of file diff --git a/Experiment/graph/Exp5/CollectionStringProcessing.mermaid b/Experiment/graph/Exp5/CollectionStringProcessing.mermaid new file mode 100644 index 0000000..81abe39 --- /dev/null +++ b/Experiment/graph/Exp5/CollectionStringProcessing.mermaid @@ -0,0 +1,26 @@ +graph TD + A[开始] --> B[初始化: 定义英文文本]; + B --> C[输出: 原始文本]; + C --> D[--- ArrayList 处理 ---]; + D --> E{预处理文本: 转小写, 去标点, 按空格拆分}; + E --> F["将拆分后的单词存入 ArrayList (wordList)"]; + F --> G[移除 ArrayList 中的空字符串]; + G --> H{"计算: wordList 的大小 (单词总数)"}; + H --> I[输出: 单词总个数]; + I --> J{创建副本并排序: 对 wordList 进行排序}; + J --> K[输出: 排序后的所有单词]; + K --> L[--- HashSet 处理 ---]; + L --> M{"创建: 从 wordList 创建 HashSet (uniqueWordsSet) 以获取不重复单词"}; + M --> N{"计算: uniqueWordsSet 的大小 (不同单词个数)"}; + N --> O[输出: 不同单词的个数]; + O --> P[输出:所有不同的单词]; + P --> Q[--- HashMap 处理 ---]; + Q --> R{"创建: 初始化空的 HashMap (wordCountMap)"}; + R --> S{遍历 wordList 中的每个单词}; + S -- 存在 --> T{更新: 单词在 wordCountMap 中已存在, 个数+1}; + S -- 不存在 --> U{添加: 单词首次出现, 存入 wordCountMap, 个数设为1}; + T --> V[遍历完所有单词]; + U --> V; + V --> W{遍历 wordCountMap}; + W --> X[输出: 每个单词及其出现的次数]; + X --> Y[结束]; diff --git a/Experiment/graph/Exp5/StringManipulation.mermaid b/Experiment/graph/Exp5/StringManipulation.mermaid new file mode 100644 index 0000000..3c50110 --- /dev/null +++ b/Experiment/graph/Exp5/StringManipulation.mermaid @@ -0,0 +1,10 @@ +graph TD + A[开始] --> B{输入: 请输入一串字符数据}; + B --> C[读取用户输入的字符串]; + C --> D{处理: 统计字符串长度}; + D --> E[输出: 字符个数]; + E --> F{处理: 将字符串转为大写}; + F --> G[输出: 大写字符串]; + G --> H{处理: 逆序大写字符串}; + H --> I[输出: 逆序后的大写字符串]; + I --> J[结束]; diff --git a/Experiment/graph/Exp5/StringReplacement.mermaid b/Experiment/graph/Exp5/StringReplacement.mermaid new file mode 100644 index 0000000..8065917 --- /dev/null +++ b/Experiment/graph/Exp5/StringReplacement.mermaid @@ -0,0 +1,7 @@ +graph TD + A[开始] --> B[初始化: 定义原始字符串]; + B --> C[输出: 原始字符串]; + C --> D{处理: 将所有 she 替换为 he}; + D --> E{处理: 将所有 She 替换为 He}; + E --> F[输出: 替换后的字符串]; + F --> G[结束]; diff --git a/Experiment/graph/Exp5/TestMyDateTools.mermaid b/Experiment/graph/Exp5/TestMyDateTools.mermaid new file mode 100644 index 0000000..03b7b5d --- /dev/null +++ b/Experiment/graph/Exp5/TestMyDateTools.mermaid @@ -0,0 +1,11 @@ +graph TD + A[开始] --> B[创建 MyDateTools 对象实例]; + B --> C1["调用 dateTools.getNow(null)"]; + C1 --> C2["输出: getNow(null) 的结果"]; + C2 --> C3["调用 dateTools.getNow('yyyy-MM-dd')"]; + C3 --> C4["输出: getNow('yyyy-MM-dd') 的结果"]; + C4 --> D1["调用 dateTools.getYear()"]; + D1 --> D2[输出: 当前年份]; + D2 --> E1["调用 dateTools.getMonth()"]; + E1 --> E2[输出: 当前月份]; + E2 --> F[结束]; diff --git a/Experiment/graph/Exp6/DivideByZero.mermaid b/Experiment/graph/Exp6/DivideByZero.mermaid new file mode 100644 index 0000000..cf5bb72 --- /dev/null +++ b/Experiment/graph/Exp6/DivideByZero.mermaid @@ -0,0 +1,11 @@ +graph TD + A[开始] --> B{初始化 num1 = 100}; + B --> C[创建 Scanner 对象 in]; + C --> D{从控制台读取整数 num2}; + D --> E{尝试块开始}; + E --> F{计算 num1 = num1 / num2}; + F --> G[打印结果 “结果为: ” + num1]; + G --> H[结束]; + E -- ArithmeticException --> I[捕获 ArithmeticException]; + I --> J[打印 “除数不能为0”]; + J --> H; \ No newline at end of file diff --git a/Experiment/graph/Exp6/ManyException.mermaid b/Experiment/graph/Exp6/ManyException.mermaid new file mode 100644 index 0000000..7434291 --- /dev/null +++ b/Experiment/graph/Exp6/ManyException.mermaid @@ -0,0 +1,23 @@ +graph TD + A[开始] --> B{第一个 try 块}; + B --> C{计算 result = 8 / 0}; + C -- ArithmeticException --> D[捕获 ArithmeticException]; + D --> E[打印 “算术异常”]; + E --> F{第二个 try 块}; + C --> F; + F --> G{获取 null 字符串的长度}; + G -- NullPointerException --> H[捕获 NullPointerException]; + H --> I[打印 “空指针异常”]; + I --> J{第三个 try 块}; + G --> J; + J --> K{创建大小为4的float数组 arr}; + K --> L{"访问 arr[4]"}; + L -- ArrayIndexOutOfBoundsException --> M[捕获 ArrayIndexOutOfBoundsException]; + M --> N[打印 “数组下标越界异常”]; + N --> O{第四个 try 块}; + L --> O; + O --> P{将字符串 '23U' 转换为 double}; + P -- NumberFormatException --> Q[捕获 NumberFormatException]; + Q --> R[打印 “字符串转换异常”]; + R --> S[结束]; + P --> S; \ No newline at end of file diff --git a/Experiment/graph/Exp6/SafeTriangle.mermaid b/Experiment/graph/Exp6/SafeTriangle.mermaid new file mode 100644 index 0000000..3d60ad6 --- /dev/null +++ b/Experiment/graph/Exp6/SafeTriangle.mermaid @@ -0,0 +1,34 @@ +graph TD + subgraph getArea 方法 + GA_A["开始 getArea(a, b, c)"] --> GA_B{判断 a+b>c 且 a+c>b 且 b+c>a}; + GA_B -- false --> GA_C[抛出 IllegalArgumentException “无法构成三角形”]; + GA_B -- true --> GA_D["计算 (a+b+c)/2"]; + GA_D --> GA_E[返回结果]; + GA_C --> GA_E; + end + + subgraph main 方法 + M_A[开始 main] --> M_B[创建 SafeTriangle 对象 triangle]; + M_B --> M_C{try 块}; + M_C --> M_D[打印 “请输入三角形的三条边长:”]; + M_D --> M_E[创建 Scanner 对象]; + M_E --> M_F[读取一行输入]; + M_F --> M_G[按空格分割输入为 parts 数组]; + M_G --> M_H{判断 parts.length < 3}; + M_H -- true --> M_I[抛出 IllegalArgumentException “请输入三条边长”]; + M_H -- false --> M_J[初始化 a, b, c = 0]; + M_J --> M_K{内部 try 块}; + M_K --> M_L["解析 parts[0] 为 a"]; + M_L --> M_M["解析 parts[1] 为 b"]; + M_M --> M_N["解析 parts[2] 为 c"]; + M_N --> M_O["调用 triangle.getArea(a, b, c) 获取面积 area"]; + M_O --> M_P[打印 “三角形面积: ” + area]; + M_P --> M_Q[结束 try 块]; + M_K -- NumberFormatException --> M_R[捕获 NumberFormatException]; + M_R --> M_S[抛出 IllegalArgumentException “边长必须是数字”]; + M_S --> M_T{捕获外部 IllegalArgumentException}; + M_I --> M_T; + M_Q --> M_U[结束 main]; + M_T --> M_V["打印异常信息 e.getMessage()"]; + M_V --> M_U; + end \ No newline at end of file diff --git a/Experiment/graph/Exp6/TransCard.mermaid b/Experiment/graph/Exp6/TransCard.mermaid new file mode 100644 index 0000000..a8071c5 --- /dev/null +++ b/Experiment/graph/Exp6/TransCard.mermaid @@ -0,0 +1,22 @@ +graph TD + subgraph pay 方法 + P_A["开始 pay(amount)"] --> P_B{判断 amount > balance}; + P_B -- true --> P_C[抛出 InsufficientBalanceException “余额不足”]; + P_B -- false --> P_D[balance -= amount]; + P_D --> P_E[打印 “支付成功,当前余额: ” + balance]; + P_E --> P_F[结束 pay]; + P_C --> P_F; + end + + subgraph main 方法 + M_A[开始 main] --> M_B[创建 TransCard 对象 card]; + M_B --> M_C[设置 card.balance = 100.0]; + M_C --> M_D{try 块}; + M_D --> M_E["调用 card.pay(50.0)"]; + M_E --> M_F["调用 card.pay(60.0)"]; + M_F --> M_G[结束 try 块]; + M_D -- InsufficientBalanceException --> M_H[捕获 InsufficientBalanceException]; + M_H --> M_I["打印异常信息 e.getMessage()"]; + M_I --> M_J[结束 main]; + M_G --> M_J; + end diff --git a/Experiment/graph/Exp7/FibonacciSeq.mermaid b/Experiment/graph/Exp7/FibonacciSeq.mermaid new file mode 100644 index 0000000..4239aef --- /dev/null +++ b/Experiment/graph/Exp7/FibonacciSeq.mermaid @@ -0,0 +1,19 @@ +flowchart TD + A[开始] --> B["定义 n=20,并创建 int[] fib"] + B --> C["fib[0]=0; fib[1]=1"] + C --> D["循环 i=2~19 计算 fib[i]=fib[i-1]+fib[i-2]"] + D --> E[生成完毕,打开 FileWriter 写入 in.txt] + E --> F[初始化 i=0] + F --> G{是否 i < n?} + G -- 是 --> H["写入 fib[i] 的字符串形式"] + H --> I{"(i+1)%5==0?"} + I -- 是 --> J["写入 \n"] + I -- 否 --> K{i < n-1?} + K -- 是 --> L["写入 , "] + K -- 否 --> M[不写分隔符] + J --> N[i++] + L --> N[i++] + M --> N[i++] + N --> G + G -- 否 --> O[关闭 FileWriter] + O --> P[程序结束] \ No newline at end of file diff --git a/Experiment/graph/Exp7/FibonacciSum.mermaid b/Experiment/graph/Exp7/FibonacciSum.mermaid new file mode 100644 index 0000000..95e709e --- /dev/null +++ b/Experiment/graph/Exp7/FibonacciSum.mermaid @@ -0,0 +1,22 @@ +flowchart TD + A[开始] --> B[初始化 sum=0] + B --> C[创建 FileReader 读取 in.txt] + C --> D[创建 StringBuilder number] + D --> E{"reader.read() 返回 ch"} + E -- != -1 --> F{"Character.isDigit(ch)?"} + F -- 是 --> G["number.append(ch 转字符)"] + F -- 否 --> H{ch 是 ',' 或 '\n'?} + H -- 是 --> I{number 是否为空?} + I -- 否 --> J["sum += Integer.parseInt(number)"] + J --> K["number.setLength(0)"] + K --> E + H -- 否 --> E + E -- == -1 --> L{"number.length()>0?"} + L -- 是 --> M["sum += Integer.parseInt(number)"] + L -- 否 --> N[跳过] + M --> N + N --> O[关闭 FileReader] + O --> P[创建 FileWriter 写入 sum.txt] + P --> Q[将 sum 转为字符串写入] + Q --> R[关闭 FileWriter] + R --> S[程序结束] diff --git a/Experiment/graph/Exp7/FileContentCopy.mermaid b/Experiment/graph/Exp7/FileContentCopy.mermaid new file mode 100644 index 0000000..a0327bb --- /dev/null +++ b/Experiment/graph/Exp7/FileContentCopy.mermaid @@ -0,0 +1,8 @@ +flowchart TD + A[开始] --> B[创建 FileReader 读取 source.txt] + B --> C[创建 FileWriter 写入 object.txt] + C --> D{"reader.read() 返回值"} + D -- != -1 --> E[将字符写入 object.txt] + E --> D + D -- == -1 --> F[关闭 reader 和 writer] + F --> G[程序结束] diff --git a/Experiment/in.txt b/Experiment/in.txt new file mode 100644 index 0000000..91d0ec7 --- /dev/null +++ b/Experiment/in.txt @@ -0,0 +1,4 @@ +0, 1, 1, 2, 3 +5, 8, 13, 21, 34 +55, 89, 144, 233, 377 +610, 987, 1597, 2584, 4181 diff --git a/Experiment/object.txt b/Experiment/object.txt new file mode 100644 index 0000000..5e1c309 --- /dev/null +++ b/Experiment/object.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/Experiment/report/实验报告-实验1.docx b/Experiment/report/实验报告-实验1.docx new file mode 100644 index 0000000..b694aed Binary files /dev/null and b/Experiment/report/实验报告-实验1.docx differ diff --git a/Experiment/report/实验报告-实验2.docx b/Experiment/report/实验报告-实验2.docx new file mode 100644 index 0000000..4775806 Binary files /dev/null and b/Experiment/report/实验报告-实验2.docx differ diff --git a/Experiment/report/实验报告-实验3.docx b/Experiment/report/实验报告-实验3.docx new file mode 100644 index 0000000..4c70be3 Binary files /dev/null and b/Experiment/report/实验报告-实验3.docx differ diff --git a/Experiment/report/实验报告-实验4.docx b/Experiment/report/实验报告-实验4.docx new file mode 100644 index 0000000..9b39d84 Binary files /dev/null and b/Experiment/report/实验报告-实验4.docx differ diff --git a/Experiment/report/实验报告-实验5.docx b/Experiment/report/实验报告-实验5.docx new file mode 100644 index 0000000..15ce78d Binary files /dev/null and b/Experiment/report/实验报告-实验5.docx differ diff --git a/Experiment/report/实验报告-实验6.docx b/Experiment/report/实验报告-实验6.docx new file mode 100644 index 0000000..d22c2e3 Binary files /dev/null and b/Experiment/report/实验报告-实验6.docx differ diff --git a/Experiment/report/实验报告-实验7.docx b/Experiment/report/实验报告-实验7.docx new file mode 100644 index 0000000..cab96ad Binary files /dev/null and b/Experiment/report/实验报告-实验7.docx differ diff --git a/Experiment/source.txt b/Experiment/source.txt new file mode 100644 index 0000000..5e1c309 --- /dev/null +++ b/Experiment/source.txt @@ -0,0 +1 @@ +Hello World \ No newline at end of file diff --git a/Experiment/src/Exp1/Task1/HelloWorld.java b/Experiment/src/Exp1/Task1/HelloWorld.java new file mode 100644 index 0000000..1dcef67 --- /dev/null +++ b/Experiment/src/Exp1/Task1/HelloWorld.java @@ -0,0 +1,7 @@ +package Exp1.Task1; + +public class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} diff --git a/Experiment/src/Exp1/Task2/Max.java b/Experiment/src/Exp1/Task2/Max.java new file mode 100644 index 0000000..86aea93 --- /dev/null +++ b/Experiment/src/Exp1/Task2/Max.java @@ -0,0 +1,18 @@ +package Exp1.Task2; + +public class Max { + public static void main(String[] args) { + int max; + int a = Integer.parseInt(args[0]); + int b = Integer.parseInt(args[1]); + int c = Integer.parseInt(args[2]); + if (a > b && a > c) { + max = a; + } else if (b > c) { + max = b; + } else { + max = c; + } + System.out.println("三个数中最大的是:" + max); + } +} diff --git a/Experiment/src/Exp1/Task2/Say.java b/Experiment/src/Exp1/Task2/Say.java new file mode 100644 index 0000000..9d73fc5 --- /dev/null +++ b/Experiment/src/Exp1/Task2/Say.java @@ -0,0 +1,13 @@ +package Exp1.Task2; + +public class Say { + public static void main(String[] args) { + if (args.length < 2) { + System.out.println("需要两个命令行参数!"); + System.exit(1); + } + String name = args[0]; + String word = args[1]; + System.out.println("我想对" + name + "悄悄地说:" + word); + } +} diff --git a/Experiment/src/Exp1/Task3/SimpleTypes.java b/Experiment/src/Exp1/Task3/SimpleTypes.java new file mode 100644 index 0000000..19aa62a --- /dev/null +++ b/Experiment/src/Exp1/Task3/SimpleTypes.java @@ -0,0 +1,22 @@ +package Exp1.Task3; + +public class SimpleTypes { + public static void main(String[] args) { + byte b = 055; + short s = 0x55FF; + int i = 1000000; + long l = 3615L; + char c = 'c'; + float f = 0.23F; + double d = 0.7E-3; + boolean bool = true; + System.out.println("b=" + b); + System.out.println("s=" + s); + System.out.println("i=" + i); + System.out.println("l=" + l); + System.out.println("c=" + c); + System.out.println("f=" + f); + System.out.println("d=" + d); + System.out.println("bool=" + bool); + } +} diff --git a/Experiment/src/Exp1/Task4/ArithmaticOp.java b/Experiment/src/Exp1/Task4/ArithmaticOp.java new file mode 100644 index 0000000..de0fdf8 --- /dev/null +++ b/Experiment/src/Exp1/Task4/ArithmaticOp.java @@ -0,0 +1,28 @@ +package Exp1.Task4; + +public class ArithmaticOp { + public static void main(String[] args) { + int a = 5 + 4; + int b = a * 2; + int c = b / 4; + int d = b - c; + int e = -d; + int f = e % 4; + double g = 18.4; + double h = g % 4; + int i = 3; + int j = i++; + int k = ++i; + System.out.println("a=" + a); + System.out.println("b=" + b); + System.out.println("c=" + c); + System.out.println("d=" + d); + System.out.println("e=" + e); + System.out.println("f=" + f); + System.out.println("g=" + g); + System.out.println("h=" + h); + System.out.println("i=" + i); + System.out.println("j=" + j); + System.out.println("k=" + k); + } +} diff --git a/Experiment/src/Exp1/Task5/ArrayRefer.java b/Experiment/src/Exp1/Task5/ArrayRefer.java new file mode 100644 index 0000000..52e8556 --- /dev/null +++ b/Experiment/src/Exp1/Task5/ArrayRefer.java @@ -0,0 +1,14 @@ +package Exp1.Task5; + +public class ArrayRefer { + public static void main(String[] args) { + int i; + int arrayA[] = new int[5]; + for (i = 0; i < 5; i++) { + arrayA[i] = i; + } + for (i = 0; i < arrayA.length; i++) { + System.out.println("arrayA[" + i + "] = " + arrayA[i]); + } + } +} diff --git a/Experiment/src/Exp1/Task6/CircleCalc.java b/Experiment/src/Exp1/Task6/CircleCalc.java new file mode 100644 index 0000000..4fac309 --- /dev/null +++ b/Experiment/src/Exp1/Task6/CircleCalc.java @@ -0,0 +1,11 @@ +package Exp1.Task6; + +public class CircleCalc { + public static void main(String[] args) { + double radius = 3.0; + double circumference = 2 * Math.PI * radius; + double area = Math.PI * radius * radius; + System.out.println("圆的周长是:" + circumference); + System.out.println("圆的面积是:" + area); + } +} diff --git a/Experiment/src/Exp1/Task6/PythagoreanTheorem.java b/Experiment/src/Exp1/Task6/PythagoreanTheorem.java new file mode 100644 index 0000000..b8bec14 --- /dev/null +++ b/Experiment/src/Exp1/Task6/PythagoreanTheorem.java @@ -0,0 +1,13 @@ +package Exp1.Task6; + +public class PythagoreanTheorem { + public static void main(String[] args) { + System.out.println("请输入直角三角形的两条直角边的长度:"); + java.util.Scanner scanner = new java.util.Scanner(System.in); + double a = scanner.nextDouble(); + double b = scanner.nextDouble(); + scanner.close(); + double c = Math.sqrt(a * a + b * b); + System.out.println("直角三角形的斜边长为:" + c); + } +} diff --git a/Experiment/src/Exp2/Task1/SortNum.java b/Experiment/src/Exp2/Task1/SortNum.java new file mode 100644 index 0000000..20dec5f --- /dev/null +++ b/Experiment/src/Exp2/Task1/SortNum.java @@ -0,0 +1,23 @@ +package Exp2.Task1; + +public class SortNum { + public static void main(String[] args) { + int a = 9, b = 5, c = 7, t; + if (a > b) { + t = a; + a = b; + b = t; + } + if (a > c) { + t = a; + a = c; + c = t; + } + if (b > c) { + t = b; + b = c; + c = t; + } + System.out.println("a=" + a + ", b=" + b + ", c=" + c); + } +} diff --git a/Experiment/src/Exp2/Task2/U2.java b/Experiment/src/Exp2/Task2/U2.java new file mode 100644 index 0000000..4d33fb4 --- /dev/null +++ b/Experiment/src/Exp2/Task2/U2.java @@ -0,0 +1,17 @@ +package Exp2.Task2; + +public class U2 { + public static void main(String[] args) { + int score = 55; + switch (score / 10) { + case 0: case 1: case 2: case 3: case 4: + case 5: System.out.println(score+"分是D等"); break; + case 6: System.out.println(score+"分是C等"); break; + case 7: + case 8: System.out.println(score+"分是B等"); break; + case 9: + case 10: System.out.println(score+"分是A等"); break; + default: System.out.println("数据错误"); break; + } + } +} diff --git a/Experiment/src/Exp2/Task3/CircularFactorial.java b/Experiment/src/Exp2/Task3/CircularFactorial.java new file mode 100644 index 0000000..898d22a --- /dev/null +++ b/Experiment/src/Exp2/Task3/CircularFactorial.java @@ -0,0 +1,16 @@ +package Exp2.Task3; + +public class CircularFactorial { + public static void main(String[] args) { + int n = 10; + int result = 1; + if (n == 0 || n == 1) { + result = 1; + } else { + for (int i = 2; i <= n; i++) { + result *= i; + } + } + System.out.println("n! = " + result); + } +} diff --git a/Experiment/src/Exp2/Task3/RecursiveFactorial.java b/Experiment/src/Exp2/Task3/RecursiveFactorial.java new file mode 100644 index 0000000..3d4b196 --- /dev/null +++ b/Experiment/src/Exp2/Task3/RecursiveFactorial.java @@ -0,0 +1,17 @@ +package Exp2.Task3; + +public class RecursiveFactorial { + public static void main(String[] args) { + int n = 10; + int result = factorial(n); + System.out.println("n! = " + result); + } + + public static int factorial(int n) { + if (n == 0 || n == 1) { + return 1; + } else { + return n * factorial(n - 1); + } + } +} diff --git a/Experiment/src/Exp2/Task4/PrimeNum.java b/Experiment/src/Exp2/Task4/PrimeNum.java new file mode 100644 index 0000000..1c1c937 --- /dev/null +++ b/Experiment/src/Exp2/Task4/PrimeNum.java @@ -0,0 +1,32 @@ +package Exp2.Task4; + +public class PrimeNum { + public static void main(String[] args) { + int start = 100; + int end = 2000; + int num_in_line = 0; + System.out.println("100~2000之间的素数有:"); + for (int i = start; i <= end; i++) { + if (isPrime(i)) { + num_in_line++; + if (num_in_line % 5 == 0) { + System.out.println(i); + } else { + System.out.print(i + " "); + } + } + } + } + + public static boolean isPrime(int n) { + if (n <= 1) { + return false; + } + for (int i = 2; i <= Math.sqrt(n); i++) { + if (n % i == 0) { + return false; + } + } + return true; + } +} diff --git a/Experiment/src/Exp3/Task1/Rectangle.java b/Experiment/src/Exp3/Task1/Rectangle.java new file mode 100644 index 0000000..0a72226 --- /dev/null +++ b/Experiment/src/Exp3/Task1/Rectangle.java @@ -0,0 +1,43 @@ +package Exp3.Task1; + +import static java.lang.Math.abs; + +public class Rectangle { + private double lx, ly, rx, ry; + public Rectangle(double rx, double ry) { + this.lx = 0; + this.ly = 0; + this.rx = rx; + this.ry = ry; + } + public Rectangle(double lx, double ly, double rx, double ry) { + this.lx = lx; + this.ly = ly; + this.rx = rx; + this.ry = ry; + } + public double getAttribute(String attribute) { + return switch (attribute) { + case "lx" -> lx; + case "ly" -> ly; + case "rx" -> rx; + case "ry" -> ry; + default -> 0; + }; + } + public void setAttribute(String attribute, double value) { + switch (attribute) { + case "lx": lx = value; break; + case "ly": ly = value; break; + case "rx": rx = value; break; + case "ry": ry = value; break; + default: System.out.println("Invalid attribute"); break; + } + } + public double getC() { + return 2 * (abs(rx - lx) + abs(ry - ly)); + } + public double getArea() { + return abs((rx - lx) * (ry - ly)); + } +} diff --git a/Experiment/src/Exp3/Task1/Test1.java b/Experiment/src/Exp3/Task1/Test1.java new file mode 100644 index 0000000..69a08f5 --- /dev/null +++ b/Experiment/src/Exp3/Task1/Test1.java @@ -0,0 +1,13 @@ +package Exp3.Task1; + +public class Test1 { + public static void main(String[] args) { + Rectangle rect1 = new Rectangle(5, 3); + System.out.println("矩形1周长: " + rect1.getC()); + System.out.println("矩形1面积: " + rect1.getArea()); + + Rectangle rect2 = new Rectangle(1, 6, 6, 2); + System.out.println("矩形2周长: " + rect2.getC()); + System.out.println("矩形2面积: " + rect2.getArea()); + } +} \ No newline at end of file diff --git a/Experiment/src/Exp3/Task2/Circle.java b/Experiment/src/Exp3/Task2/Circle.java new file mode 100644 index 0000000..cccb396 --- /dev/null +++ b/Experiment/src/Exp3/Task2/Circle.java @@ -0,0 +1,24 @@ +package Exp3.Task2; + +public class Circle { + private double radius, perimeter, area; + public Circle() { + this.radius = 0; + this.perimeter = 0; + this.area = 0; + } + public Circle(double radius) { + this.radius = radius; + this.perimeter = 2 * Math.PI * radius; + this.area = Math.PI * radius * radius; + } + public double getRadius() { + return radius; + } + public double getPerimeter() { + return perimeter; + } + public double getArea() { + return area; + } +} diff --git a/Experiment/src/Exp3/Task2/CircleTest.java b/Experiment/src/Exp3/Task2/CircleTest.java new file mode 100644 index 0000000..026e023 --- /dev/null +++ b/Experiment/src/Exp3/Task2/CircleTest.java @@ -0,0 +1,10 @@ +package Exp3.Task2; + +public class CircleTest { + public static void main(String[] args) { + Circle c = new Circle(5); + System.out.println("半径为:" + c.getRadius()); + System.out.println("周长为:" + c.getPerimeter()); + System.out.println("面积为:" + c.getArea()); + } +} diff --git a/Experiment/src/Exp3/Task2/Person.java b/Experiment/src/Exp3/Task2/Person.java new file mode 100644 index 0000000..62f1a30 --- /dev/null +++ b/Experiment/src/Exp3/Task2/Person.java @@ -0,0 +1,26 @@ +package Exp3.Task2; + +import java.time.LocalDate; + +public class Person { + private int IdPerson; + private String Name; + private char Sex; + private LocalDate Birthday; + private String HomeAddress; + + public void addPerson(int id, String name, char sex, LocalDate birthday, String homeAddress) { + this.IdPerson = id; + this.Name = name; + this.Sex = sex; + this.Birthday = birthday; + this.HomeAddress = homeAddress; + } + public void showPerson() { + System.out.println("Id: " + IdPerson); + System.out.println("Name: " + Name); + System.out.println("Sex: " + Sex); + System.out.println("Birthday: " + Birthday); + System.out.println("Home Address: " + HomeAddress); + } +} diff --git a/Experiment/src/Exp3/Task2/PersonTest.java b/Experiment/src/Exp3/Task2/PersonTest.java new file mode 100644 index 0000000..0f201ac --- /dev/null +++ b/Experiment/src/Exp3/Task2/PersonTest.java @@ -0,0 +1,11 @@ +package Exp3.Task2; + +import java.time.LocalDate; + +public class PersonTest { + public static void main(String[] args) { + Person p = new Person(); + p.addPerson(123, "John Doe", 'M', LocalDate.of(1990, 1, 1), "123 Main St"); + p.showPerson(); + } +} diff --git a/Experiment/src/Exp4/Task1/BackAnimal.java b/Experiment/src/Exp4/Task1/BackAnimal.java new file mode 100644 index 0000000..ec4c899 --- /dev/null +++ b/Experiment/src/Exp4/Task1/BackAnimal.java @@ -0,0 +1,52 @@ +package Exp4.Task1; + +abstract class Animal { + public abstract void eat(); //只有方法名,而没有方法体 +} + +class Dog extends Animal { + private String name; + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void eat() { + System.out.println("小狗啃骨头啦"); + } +} + +class Bird extends Animal { + public void fly() { + System.out.println("小鸟飞呀飞呀"); + } + + public void eat() { + System.out.println("小鸟吃虫子啦"); + } +} + +public class BackAnimal { + public static void main(String args[]) { + // Animal a1 = new Animal(); //1.该行代码可不可以执行?为什么? + Animal an = new Dog(); + an.eat(); //2.该行代码输出什么? + an = new Bird(); + an.eat(); //3.该行代码输出什么? + Animal x1 = new Dog(); + Animal x2 = new Bird(); + print(x1); //4.以下2行代码输出什么?为什么? + print(x2); + + } + + public static void print(Animal a) { + a.eat(); + } +} + + diff --git a/Experiment/src/Exp4/Task2/AbstractGuessNumber.java b/Experiment/src/Exp4/Task2/AbstractGuessNumber.java new file mode 100644 index 0000000..39ce0d6 --- /dev/null +++ b/Experiment/src/Exp4/Task2/AbstractGuessNumber.java @@ -0,0 +1,22 @@ +package Exp4.Task2; + +public abstract class AbstractGuessNumber { + private int number, guess = 0; + public void setNumber() { + System.out.println("想一个数让他猜去,"); + this.number = getUserInput(); + } + protected abstract void showMessage(String message); + protected abstract int getUserInput(); + public void begin() { + showMessage("欢迎玩猜数字游戏!\n"); + while (number != guess) { + guess = getUserInput(); + if (number < guess) + showMessage("猜大了,别泄气哦\n"); + if (number > guess) + showMessage("猜小了,别泄气哦\n"); + } + showMessage("你可算猜对了\n"); + } +} diff --git a/Experiment/src/Exp4/Task2/ExtendsGuessNumber.java b/Experiment/src/Exp4/Task2/ExtendsGuessNumber.java new file mode 100644 index 0000000..bd045f7 --- /dev/null +++ b/Experiment/src/Exp4/Task2/ExtendsGuessNumber.java @@ -0,0 +1,24 @@ +package Exp4.Task2; + +import java.util.Scanner; + +public class ExtendsGuessNumber extends AbstractGuessNumber { + private Scanner scanner; + public ExtendsGuessNumber() { + scanner = new Scanner(System.in); + } + public void showMessage(String message) { + for (int i = 0; i < message.length() * 2; i++) { + System.out.print("*"); + } + System.out.println("\n" + message); + for (int i = 0; i < message.length() * 2; i++) { + System.out.print("*"); + } + System.out.println("\n"); + } + public int getUserInput() { + System.out.println("请输入一个数吧:"); + return scanner.nextInt(); + } +} diff --git a/Experiment/src/Exp4/Task2/Start.java b/Experiment/src/Exp4/Task2/Start.java new file mode 100644 index 0000000..92cb22f --- /dev/null +++ b/Experiment/src/Exp4/Task2/Start.java @@ -0,0 +1,9 @@ +package Exp4.Task2; + +public class Start { + public static void main(String[] args) { + AbstractGuessNumber egu = new ExtendsGuessNumber(); + egu.setNumber(); + egu.begin(); + } +} diff --git a/Experiment/src/Exp4/Task3/Father.java b/Experiment/src/Exp4/Task3/Father.java new file mode 100644 index 0000000..80e9162 --- /dev/null +++ b/Experiment/src/Exp4/Task3/Father.java @@ -0,0 +1,25 @@ +package Exp4.Task3; + +public abstract class Father { + protected double height; + protected double weight; + public Father(double height, double weight) { + this.height = height; + this.weight = weight; + } + public double getHeight() { + return height; + } + public void setHeight(double height) { + this.height = height; + } + public double getWeight() { + return weight; + } + public void setWeight(double weight) { + this.weight = weight; + } + public void hobby() { + System.out.println("父亲喜欢唱歌!"); + } +} diff --git a/Experiment/src/Exp4/Task3/Main.java b/Experiment/src/Exp4/Task3/Main.java new file mode 100644 index 0000000..7216b5d --- /dev/null +++ b/Experiment/src/Exp4/Task3/Main.java @@ -0,0 +1,11 @@ +package Exp4.Task3; + +public class Main { + public static void main(String[] args) { + Son son = new Son(180.0, 70.0, "外向"); + System.out.println("儿子的身高:" + son.getHeight() + "厘米"); + System.out.println("儿子的体重:" + son.getWeight() + "公斤"); + System.out.println("儿子的性格:" + son.getPersonality()); + son.hobby(); + } +} diff --git a/Experiment/src/Exp4/Task3/Son.java b/Experiment/src/Exp4/Task3/Son.java new file mode 100644 index 0000000..6a82f78 --- /dev/null +++ b/Experiment/src/Exp4/Task3/Son.java @@ -0,0 +1,19 @@ +package Exp4.Task3; + +public class Son extends Father { + private String personality; + public Son(double height, double weight, String personality) { + super(height, weight); + this.personality = personality; + } + public String getPersonality() { + return personality; + } + public void setPersonality(String personality) { + this.personality = personality; + } + @Override + public void hobby() { + System.out.println("儿子也喜欢唱歌,但唱的是流行歌曲!"); + } +} diff --git a/Experiment/src/Exp4/Task4/Class1.java b/Experiment/src/Exp4/Task4/Class1.java new file mode 100644 index 0000000..8b315de --- /dev/null +++ b/Experiment/src/Exp4/Task4/Class1.java @@ -0,0 +1,12 @@ +package Exp4.Task4; + +public class Class1 { + RRect rect; + public static void main(String[] args) { + RRect rect = new RRect(); + System.out.println("矩形的长" + rect.getx()); + System.out.println("矩形的宽" + rect.gety()); + System.out.println("矩形的面积" + rect.calarea()); + System.out.println("矩形的周长" + rect.calgirth()); + } +} diff --git a/Experiment/src/Exp4/Task4/RRect.java b/Experiment/src/Exp4/Task4/RRect.java new file mode 100644 index 0000000..60cc919 --- /dev/null +++ b/Experiment/src/Exp4/Task4/RRect.java @@ -0,0 +1,21 @@ +package Exp4.Task4; + +class RRect implements calrect{ + private int x; + private int y; + public RRect() { + x = 3; y = 4; + } + public int calarea() { + return x * y; + } + public int calgirth() { + return x * 2 + y * 2; + } + public int getx() { + return x; + } + public int gety() { + return y; + } +} diff --git a/Experiment/src/Exp4/Task4/calrect.java b/Experiment/src/Exp4/Task4/calrect.java new file mode 100644 index 0000000..b3f1a2b --- /dev/null +++ b/Experiment/src/Exp4/Task4/calrect.java @@ -0,0 +1,8 @@ +package Exp4.Task4; + +public interface calrect { + public abstract int calarea(); + public abstract int calgirth(); + public abstract int getx(); + public abstract int gety(); +} diff --git a/Experiment/src/Exp4/Task5/Circle.java b/Experiment/src/Exp4/Task5/Circle.java new file mode 100644 index 0000000..d98369d --- /dev/null +++ b/Experiment/src/Exp4/Task5/Circle.java @@ -0,0 +1,17 @@ +package Exp4.Task5; + +public class Circle implements Graphic{ + private double radius; + public Circle(double radius){ + this.radius = radius; + } + public double area(){ + return Math.PI * radius * radius; + } + public double perimeter(){ + return 2 * Math.PI * radius; + } + public double getRadius(){ + return radius; + } +} diff --git a/Experiment/src/Exp4/Task5/Graphic.java b/Experiment/src/Exp4/Task5/Graphic.java new file mode 100644 index 0000000..8db0077 --- /dev/null +++ b/Experiment/src/Exp4/Task5/Graphic.java @@ -0,0 +1,6 @@ +package Exp4.Task5; + +public interface Graphic { + public abstract double area(); + public abstract double perimeter(); +} diff --git a/Experiment/src/Exp4/Task5/Rectangle.java b/Experiment/src/Exp4/Task5/Rectangle.java new file mode 100644 index 0000000..9819cf4 --- /dev/null +++ b/Experiment/src/Exp4/Task5/Rectangle.java @@ -0,0 +1,22 @@ +package Exp4.Task5; + +public class Rectangle implements Graphic{ + private double width; + private double height; + public Rectangle(double width, double height){ + this.width = width; + this.height = height; + } + public double area(){ + return width * height; + } + public double perimeter(){ + return 2 * (width + height); + } + public double getWidth(){ + return width; + } + public double getHeight(){ + return height; + } +} diff --git a/Experiment/src/Exp4/Task5/Test.java b/Experiment/src/Exp4/Task5/Test.java new file mode 100644 index 0000000..3f5292c --- /dev/null +++ b/Experiment/src/Exp4/Task5/Test.java @@ -0,0 +1,15 @@ +package Exp4.Task5; + +public class Test { + public static void main(String[] args) { + Circle c = new Circle(5); + System.out.println("圆的半径为:" + c.getRadius()); + System.out.println("圆的面积为:" + c.area()); + System.out.println("圆的周长为:" + c.perimeter()); + Rectangle r = new Rectangle(5, 3); + System.out.println("矩形的长为:" + r.getWidth()); + System.out.println("矩形的宽为:" + r.getHeight()); + System.out.println("矩形的面积为:" + r.area()); + System.out.println("矩形的周长为:" + r.perimeter()); + } +} diff --git a/Experiment/src/Exp5/Task1/StringManipulation.java b/Experiment/src/Exp5/Task1/StringManipulation.java new file mode 100644 index 0000000..ee5ece7 --- /dev/null +++ b/Experiment/src/Exp5/Task1/StringManipulation.java @@ -0,0 +1,18 @@ +package Exp5.Task1; + +import java.util.Scanner; + +public class StringManipulation { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("请输入一串字符数据:"); + String inputString = scanner.nextLine(); + int charCount = inputString.length(); + System.out.println("字符串中的字符个数为:" + charCount); + String upperCaseString = inputString.toUpperCase(); + System.out.println("转换为大写:" + upperCaseString); + StringBuilder reversedString = new StringBuilder(upperCaseString); + System.out.println("逆序输出(大写):" + reversedString.reverse().toString()); + scanner.close(); + } +} diff --git a/Experiment/src/Exp5/Task2/StringReplacement.java b/Experiment/src/Exp5/Task2/StringReplacement.java new file mode 100644 index 0000000..7e9305f --- /dev/null +++ b/Experiment/src/Exp5/Task2/StringReplacement.java @@ -0,0 +1,13 @@ +package Exp5.Task2; + +public class StringReplacement { + public static void main(String[] args) { + String originalString = "When she was young, she was very poor. She worked and studied hard. Several years later, she became rich."; + System.out.println("原始字符串:"); + System.out.println(originalString); + String replacedString = originalString.replace("she", "he"); + replacedString = replacedString.replace("She", "He"); + System.out.println("\n替换后的字符串:"); + System.out.println(replacedString); + } +} diff --git a/Experiment/src/Exp5/Task3/CollectionStringProcessing.java b/Experiment/src/Exp5/Task3/CollectionStringProcessing.java new file mode 100644 index 0000000..b4ce355 --- /dev/null +++ b/Experiment/src/Exp5/Task3/CollectionStringProcessing.java @@ -0,0 +1,48 @@ +package Exp5.Task3; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CollectionStringProcessing { + public static void main(String[] args) { + String text = "When she was young, she was very poor. She worked and studied hard. Several years later, she became rich."; + System.out.println("原始文本:"); + System.out.println(text); + // ArrayList + String cleanedText = text.toLowerCase().replaceAll("[^a-zA-Z ]", ""); + String[] wordsArray = cleanedText.split("\\s+"); + List wordList = new ArrayList<>(Arrays.asList(wordsArray)); + wordList.removeAll(Collections.singleton("")); + System.out.println("单词总个数:" + wordList.size()); + ArrayList sortedWordList = new ArrayList<>(wordList); + Collections.sort(sortedWordList); + System.out.println("排序后的单词:"); + for (String word : sortedWordList) { + System.out.print(word + " "); + } + System.out.println(); + // Hashset + Set uniqueWordsSet = new HashSet<>(wordList); + System.out.println("不同的单词个数:" + uniqueWordsSet.size()); + System.out.println("不同的单词:"); + for (String word : uniqueWordsSet) { + System.out.print(word + " "); + } + System.out.println(); + // Hashmap + Map wordCountMap = new HashMap<>(); + for (String word : wordList) { + wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1); + } + System.out.println("每个单词出现的次数:"); + for (Map.Entry entry : wordCountMap.entrySet()) { + System.out.println("单词 '" + entry.getKey() + "': " + entry.getValue() + " 次"); + } + } +} diff --git a/Experiment/src/Exp5/Task4/MyDateTools.java b/Experiment/src/Exp5/Task4/MyDateTools.java new file mode 100644 index 0000000..cffeb2f --- /dev/null +++ b/Experiment/src/Exp5/Task4/MyDateTools.java @@ -0,0 +1,27 @@ +package Exp5.Task4; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +class MyDateTools { + public String getNow(String model) { + Date now = new Date(); + if (model == null) { + return now.toString(); + } else { + SimpleDateFormat sdf = new SimpleDateFormat(model); + return sdf.format(now); + } + } + + public String getYear() { + Calendar calendar = Calendar.getInstance(); + return String.valueOf(calendar.get(Calendar.YEAR)); + } + + public String getMonth() { + Calendar calendar = Calendar.getInstance(); + return String.valueOf(calendar.get(Calendar.MONTH) + 1); + } +} \ No newline at end of file diff --git a/Experiment/src/Exp5/Task4/TestMyDateTools.java b/Experiment/src/Exp5/Task4/TestMyDateTools.java new file mode 100644 index 0000000..c987ce1 --- /dev/null +++ b/Experiment/src/Exp5/Task4/TestMyDateTools.java @@ -0,0 +1,12 @@ +package Exp5.Task4; + +public class TestMyDateTools { + public static void main(String[] args) { + MyDateTools dateTools = new MyDateTools(); + System.out.println("当前系统时间: " + dateTools.getNow(null)); + System.out.println("当前年月日: " + dateTools.getNow("yyyy-MM-dd")); + System.out.println("当前年份: " + dateTools.getYear()); + System.out.println("当前月份: " + dateTools.getMonth()); + } +} + diff --git a/Experiment/src/Exp6/Task1/DivideByZero.java b/Experiment/src/Exp6/Task1/DivideByZero.java new file mode 100644 index 0000000..08fb635 --- /dev/null +++ b/Experiment/src/Exp6/Task1/DivideByZero.java @@ -0,0 +1,17 @@ +package Exp6.Task1; + +import java.util.Scanner; + +public class DivideByZero { + public static void main(String[] args) { + int num1 = 100; + Scanner in = new Scanner(System.in); + int num2 = in.nextInt(); + try { + num1 = num1 / num2; + System.out.println("结果为: " + num1); + } catch (ArithmeticException e) { + System.out.println("除数不能为0"); + } + } +} diff --git a/Experiment/src/Exp6/Task2/ManyException.java b/Experiment/src/Exp6/Task2/ManyException.java new file mode 100644 index 0000000..c496873 --- /dev/null +++ b/Experiment/src/Exp6/Task2/ManyException.java @@ -0,0 +1,29 @@ +package Exp6.Task2; + +public class ManyException { + public static void main(String[] args) { + try { + int result = 8 / 0; + } catch (ArithmeticException e) { + System.out.println("算术异常"); + } + try { + String str = null; + int len = str.length(); + } catch (NullPointerException e) { + System.out.println("空指针异常"); + } + try { + float[] arr = new float[4]; + arr[4] = 9; + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("数组下标越界异常"); + } + try { + String str = "23U"; + double d = Double.parseDouble(str); + } catch (NumberFormatException e) { + System.out.println("字符串转换异常"); + } + } +} diff --git a/Experiment/src/Exp6/Task3/SafeTriangle.java b/Experiment/src/Exp6/Task3/SafeTriangle.java new file mode 100644 index 0000000..0c66056 --- /dev/null +++ b/Experiment/src/Exp6/Task3/SafeTriangle.java @@ -0,0 +1,38 @@ +package Exp6.Task3; + +import java.util.Scanner; + +public class SafeTriangle { + public double getArea(double a, double b, double c) { + if (!(a + b > c && a + c > b && b + c > a)) { + throw new IllegalArgumentException("无法构成三角形"); + } + return (a + b + c) / 2; + } + public static void main(String[] args) { + SafeTriangle triangle = new SafeTriangle(); + try { + System.out.println("请输入三角形的三条边长:"); + Scanner scanner = new Scanner(System.in); + String input = scanner.nextLine(); + String[] parts = input.split(" "); + if (parts.length < 3) { + throw new IllegalArgumentException("请输入三条边长"); + } + double a = 0; + double b = 0; + double c = 0; + try { + a = Double.parseDouble(parts[0]); + b = Double.parseDouble(parts[1]); + c = Double.parseDouble(parts[2]); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("边长必须是数字"); + } + double area = triangle.getArea(a, b, c); + System.out.println("三角形面积: " + area); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/Experiment/src/Exp6/Task4/InsufficientBalanceException.java b/Experiment/src/Exp6/Task4/InsufficientBalanceException.java new file mode 100644 index 0000000..c7efe4e --- /dev/null +++ b/Experiment/src/Exp6/Task4/InsufficientBalanceException.java @@ -0,0 +1,7 @@ +package Exp6.Task4; + +public class InsufficientBalanceException extends RuntimeException { + public InsufficientBalanceException(String message) { + super(message); + } +} diff --git a/Experiment/src/Exp6/Task4/TransCard.java b/Experiment/src/Exp6/Task4/TransCard.java new file mode 100644 index 0000000..72f7372 --- /dev/null +++ b/Experiment/src/Exp6/Task4/TransCard.java @@ -0,0 +1,22 @@ +package Exp6.Task4; + +public class TransCard { + private double balance; + public void pay(double amount) { + if (amount > balance) { + throw new InsufficientBalanceException("余额不足"); + } + balance -= amount; + System.out.println("支付成功,当前余额: " + balance); + } + public static void main(String[] args) { + TransCard card = new TransCard(); + card.balance = 100.0; + try { + card.pay(50.0); + card.pay(60.0); + } catch (InsufficientBalanceException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/Experiment/src/Exp7/Task1/FileContentCopy.java b/Experiment/src/Exp7/Task1/FileContentCopy.java new file mode 100644 index 0000000..5a42a47 --- /dev/null +++ b/Experiment/src/Exp7/Task1/FileContentCopy.java @@ -0,0 +1,18 @@ +package Exp7.Task1; + +import java.io.FileReader; +import java.io.FileWriter; + +public class FileContentCopy { + public static void main(String[] args) { + try (FileReader reader = new FileReader("source.txt"); + FileWriter writer = new FileWriter("object.txt")) { + int ch; + while ((ch = reader.read()) != -1) { + writer.write(ch); + } + } catch (java.io.IOException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/Experiment/src/Exp7/Task2/FibonacciSeq.java b/Experiment/src/Exp7/Task2/FibonacciSeq.java new file mode 100644 index 0000000..dc7c31d --- /dev/null +++ b/Experiment/src/Exp7/Task2/FibonacciSeq.java @@ -0,0 +1,27 @@ +package Exp7.Task2; + +import java.io.FileWriter; + +public class FibonacciSeq { + public static void main(String[] args) { + int n = 20; + int[] fib = new int[n]; + fib[0] = 0; + fib[1] = 1; + for (int i = 2; i < n; i++) { + fib[i] = fib[i - 1] + fib[i - 2]; + } + try (FileWriter writer = new FileWriter("in.txt")) { + for (int i = 0; i < n; i++) { + writer.write(fib[i] + ""); + if ((i + 1) % 5 == 0) { + writer.write("\n"); + } else if (i < n - 1) { + writer.write(", "); + } + } + } catch (java.io.IOException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/Experiment/src/Exp7/Task3/FibonacciSum.java b/Experiment/src/Exp7/Task3/FibonacciSum.java new file mode 100644 index 0000000..9e0a080 --- /dev/null +++ b/Experiment/src/Exp7/Task3/FibonacciSum.java @@ -0,0 +1,31 @@ +package Exp7.Task3; + +import java.io.FileReader; +import java.io.FileWriter; + +public class FibonacciSum { + public static void main(String[] args) { + int sum = 0; + try (FileReader reader = new FileReader("in.txt")) { + StringBuilder number = new StringBuilder(); + int ch; + while ((ch = reader.read()) != -1) { + if (Character.isDigit(ch)) { + number.append((char) ch); + } else if (ch == ',' || ch == '\n') { + if (!number.isEmpty()) { + sum += Integer.parseInt(number.toString()); + number.setLength(0); + } + } + } + } catch (java.io.IOException e) { + System.out.println(e.getMessage()); + } + try (FileWriter writer = new FileWriter("sum.txt")) { + writer.write(Integer.toString(sum)); + } catch (java.io.IOException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/Experiment/src/Extra/Ball/Class1.java b/Experiment/src/Extra/Ball/Class1.java new file mode 100644 index 0000000..303bada --- /dev/null +++ b/Experiment/src/Extra/Ball/Class1.java @@ -0,0 +1,23 @@ +package Extra.Ball; + +public class Class1 { + public static void main(String[] args) { + B b = new B(); + b.myPrint(1.2f); + } +} + +class A { + float rear(float r) { + return (float)Math.PI * r * r; + } +} + +class B extends A { + float rear(float r) { + return 4 * (float)Math.PI * r * r; + } + void myPrint(float r) { + System.out.println("半径为 " + r + " 的圆的面积=" + super.rear(r) + " 同半径的球的表面积=" + rear(r)); + } +} \ No newline at end of file diff --git a/Experiment/src/Extra/MaxArray/Test.java b/Experiment/src/Extra/MaxArray/Test.java new file mode 100644 index 0000000..405040c --- /dev/null +++ b/Experiment/src/Extra/MaxArray/Test.java @@ -0,0 +1,21 @@ +package Extra.MaxArray; + +class MaxArray { + int findmax(int a[], int n){ + int max = a[0]; + for (int i = 1; i < n; i++) { + if (a[i] > max) { + max = a[i]; + } + } + return max; + } +} +public class Test { + public static void main(String[] args) { + MaxArray ob = new MaxArray(); + int a[] = {2, 5, 7, 3, 18, 9}, b[] = {33, 43, 6, 12, 8}; + System.out.println("数组a中的最大值是" + ob.findmax(a, 6)); + System.out.println("数组b中的最大值是" + ob.findmax(b, 5)); + } +} \ No newline at end of file diff --git a/Experiment/src/Extra/Person/Test.java b/Experiment/src/Extra/Person/Test.java new file mode 100644 index 0000000..fbcd23c --- /dev/null +++ b/Experiment/src/Extra/Person/Test.java @@ -0,0 +1,26 @@ +package Extra.Person; + +class Person { + String name; + char sex; + int age; + public Person(String s, char c, int i) { + name = s; + sex = c; + age = i; + } + public String toString() { + String s = "姓名:" + name + " 性别:" + sex + " 年龄:" + age; + return s; + } +} +public class Test { + public static void main(String[] args) { + Person p1 = new Person("张三", '男', 20); + Person p2 = new Person("李四", '女', 28); + p1.sex = '女'; + System.out.println(p1.toString()); + p2.age = 33; + System.out.println(p2.toString()); + } +} diff --git a/Experiment/sum.txt b/Experiment/sum.txt new file mode 100644 index 0000000..15f29f9 --- /dev/null +++ b/Experiment/sum.txt @@ -0,0 +1 @@ +10945 \ No newline at end of file diff --git a/Java课后实战训练手册(75页).pdf b/Java课后实战训练手册(75页).pdf new file mode 100644 index 0000000..4b9056f Binary files /dev/null and b/Java课后实战训练手册(75页).pdf differ diff --git a/untitled/.gitignore b/untitled/.gitignore new file mode 100644 index 0000000..f68d109 --- /dev/null +++ b/untitled/.gitignore @@ -0,0 +1,29 @@ +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/untitled/.idea/.gitignore b/untitled/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/untitled/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/untitled/.idea/misc.xml b/untitled/.idea/misc.xml new file mode 100644 index 0000000..6f29fee --- /dev/null +++ b/untitled/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/untitled/.idea/modules.xml b/untitled/.idea/modules.xml new file mode 100644 index 0000000..3007dae --- /dev/null +++ b/untitled/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/untitled/.idea/vcs.xml b/untitled/.idea/vcs.xml new file mode 100644 index 0000000..d843f34 --- /dev/null +++ b/untitled/.idea/vcs.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/untitled/src/test.java b/untitled/src/test.java new file mode 100644 index 0000000..460a9e2 --- /dev/null +++ b/untitled/src/test.java @@ -0,0 +1,17 @@ +public class test { + public static void main(String[] args) { + char c='A'; + int i=1; + double d=2.5; + boolean b=true; + final double SALES_TAX_RATE=7.5; + String s="Hello Again"; + System.out.println("c="+c); + System.out.println("i="+i); + System.out.println("d="+d); + System.out.println("b="+b); + System.out.println("SALES_TAX_RATE="+SALES_TAX_RATE); + System.out.println("s="+s); + System.out.println("length of s="+s.length()); + } +} diff --git a/untitled/untitled.iml b/untitled/untitled.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/untitled/untitled.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/实验报告模板/JavaEE基础教程实验指导与习题解析.pdf b/实验报告模板/JavaEE基础教程实验指导与习题解析.pdf new file mode 100644 index 0000000..4877df5 Binary files /dev/null and b/实验报告模板/JavaEE基础教程实验指导与习题解析.pdf differ diff --git a/实验报告模板/实验1-全部作业.txt b/实验报告模板/实验1-全部作业.txt new file mode 100644 index 0000000..059206d --- /dev/null +++ b/实验报告模板/实验1-全部作业.txt @@ -0,0 +1,13 @@ +实验指导书: +1、P171页, 环境测试,要求如P172页,在Eclipse中新建项目以及Java文件,输入P172页(1)中的代码,运行程序,测试输出结果 +2、P172页,第4题(1),输入相应代码 +(1)直接运行,查看输出结果 +(2)在Eclipse的运行环境中输入2个参数,查看运行结果。 +得出结论与心得。 +3、P173页,第5题(写到实验报告) +4、P175页,第1题,第2题(写到实验报告),第3题, +5、P179页,编程题,第1题(写到实验报告) +6、P9页,例2.1.3(写到实验报告) +7、P9页,例2.1.4 + + diff --git a/实验报告模板/实验报告4/BackAnimal.java b/实验报告模板/实验报告4/BackAnimal.java new file mode 100644 index 0000000..95f50f4 --- /dev/null +++ b/实验报告模板/实验报告4/BackAnimal.java @@ -0,0 +1,44 @@ +package ch04; + +abstract class Animal{ + public abstract void eat(); //ֻзûз +} +class Dog extends Animal{ + private String name; + public void setName(String name){ + this.name=name; + } + public String getName(){ + return name; + } + public void eat(){ + System.out.println("Сйͷ"); + } + } +class Bird extends Animal{ + public void fly( ){ + System.out.println("Сѽѽ"); + } + public void eat( ){ + System.out.println("СԳ"); + } +} +public class BackAnimal{ + public static void main( String args[ ] ){ + Animal a1=new Animal(); //1.дɲִУΪʲô + Animal an = new Dog( ); + an.eat( ); //2.дʲô + an=new Bird(); + an.eat(); //3.дʲô + Animal x1=new Dog(); + Animal x2=new Bird(); + print(x1); //4.2дʲôΪʲô + print(x2); + + } + public static void print(Animal a){ + a.eat(); + } +} + + diff --git a/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Sobject.java b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Sobject.java new file mode 100644 index 0000000..eb428d3 --- /dev/null +++ b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Sobject.java @@ -0,0 +1,28 @@ +package com.ex4; + +public class Sobject { + private String name; + private double weight; // + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public double getWeight() { + return weight; + } + public void setWeight(double weight) { + this.weight = weight; + } + public Sobject(String name, double weight) { + this.name = name; + this.weight = weight; + } + + public void print() { + System.out.println("name:"+name+",weight:"+weight); + } + + +} diff --git a/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Table.java b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Table.java new file mode 100644 index 0000000..1df0644 --- /dev/null +++ b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Table.java @@ -0,0 +1,28 @@ +package com.ex4; + +public class Table extends Sobject{ + private double width; // + private double length; // + private double height; //߶ + + //಻д췽ϵͳԶΪ Tableһ޲Ĺ췽 + //޲ι췽УԶSobjectе޲Ĺ췽 +// public Table() { +// super(); +//// super("abc",34.5); +// } +// + public Table(String name,double weight,double width,double length,double height) { + super(name, weight); + this.width=width; + this.length=length; + this.height=height; + + } + public double area() { + return width*length; + } + public void changeWeight(double w) { + setWeight(w); + } +} diff --git a/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Test.java b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Test.java new file mode 100644 index 0000000..ebcdb57 --- /dev/null +++ b/实验报告模板/实验报告4/ex4-2023.11.01版第4题分析/Test.java @@ -0,0 +1,15 @@ +package com.ex4; + +public class Test { + + public static void main(String[] args) { + // TODO Auto-generated method stub + Table table=new Table("A1", 23, 1.8, 2.3, 0.8); + double area=table.area(); + table.changeWeight(45); + System.out.println(area); + System.out.println(table.getWeight()); + + } + +} diff --git a/实验报告模板/实验报告4/实验报告模板-实验4 - 2023.11.01.doc b/实验报告模板/实验报告4/实验报告模板-实验4 - 2023.11.01.doc new file mode 100644 index 0000000..bd95a9e Binary files /dev/null and b/实验报告模板/实验报告4/实验报告模板-实验4 - 2023.11.01.doc differ diff --git a/实验报告模板/实验报告4/实验报告模板-实验4.doc b/实验报告模板/实验报告4/实验报告模板-实验4.doc new file mode 100644 index 0000000..2b45105 Binary files /dev/null and b/实验报告模板/实验报告4/实验报告模板-实验4.doc differ diff --git a/实验报告模板/实验报告4/实验讲课.txt b/实验报告模板/实验报告4/实验讲课.txt new file mode 100644 index 0000000..cf5512a --- /dev/null +++ b/实验报告模板/实验报告4/实验讲课.txt @@ -0,0 +1,18 @@ +接口 +若类中的所有的方法都是抽象方法,并且没有成员变量----->接口 + +抽象类:可以有成员变量、可以有普通方法、可以有抽象方法 +接口: + (1)没有成员变量,只有常量与抽象方法,接口中定义的所有方法都是抽象方法 + (2)即接口不可以直接创建象,接口必须通过派生子类来创建对象 + (3)接口中所有方法都必须在子类中重写。 + (4)接口中可以定义常量 + int footnum=2;<===>public final static int footnum=2; + (5)接口可以多继承,1个类可以继承多个接口,但1个类只能继承1个父类 + +final,staic +public final static int footernum=-1; //定义了静态、常量,可以通过类名调用 +public static int footernum=-1; //静态常量,该变量可以被类创建的所有对象共享,可以通过类名调用 +public final int footernum=-1; //常量,该常量,必须通过对象名来调用 + +设计1个用户,用户有用户名,密码属性,登录,注册(动作、方法) diff --git a/实验报告模板/实验报告6/p14/BusCard.java b/实验报告模板/实验报告6/p14/BusCard.java new file mode 100644 index 0000000..7ce5766 --- /dev/null +++ b/实验报告模板/实验报告6/p14/BusCard.java @@ -0,0 +1,23 @@ +package com.p14; + +public class BusCard { + private float balance; + public BusCard() { + balance=0; + } + public float queryBalance() { + return balance; + } + public void charge(float money) { + balance=balance+money; + } + public void swipe(float money) throws CardException{ + if(balance