Java 集合实战练习题

题目 1:学生管理系统(ArrayList 应用)

题目描述

设计一个学生管理系统,使用 ArrayList 存储学生信息(包括学号 String、姓名 String、年龄 int 和成绩 double),并实现以下功能:

  1. 添加学生信息
  2. 删除指定学号的学生信息
  3. 修改指定学号的学生信息
  4. 查询指定学号的学生信息
  5. 按照从高到低的顺序排序并输出学生信息

要求

  • 使用 ArrayList 存储学生对象。
  • 学生信息包括学号(String)、姓名(String)、年龄(int)和成绩(double)。
  • 通过控制台输入输出进行交互。

解答

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

// 学生类
class Student {
    private String id;
    private String name;
    private int age;
    private double score;

    public Student(String id, String name, int age, double score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }

    // Getter 和 Setter 方法
    public String getId() { return id; }
    public String getName() { return name; }
    public int getAge() { return age; }
    public double getScore() { return score; }
    public void setId(String id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setAge(int age) { this.age = age; }
    public void setScore(double score) { this.score = score; }

    @Override
    public String toString() {
        return "学号:" + id + ",姓名:" + name + ",年龄:" + age + ",成绩:" + score;
    }
}

public class StudentManagementSystem {
    private static ArrayList<Student> studentList = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 学生管理系统 =====");
            System.out.println("1. 添加学生");
            System.out.println("2. 删除学生");
            System.out.println("3. 修改学生");
            System.out.println("4. 查询学生");
            System.out.println("5. 排序并输出学生");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addStudent();
                    break;
                case 2:
                    deleteStudent();
                    break;
                case 3:
                    updateStudent();
                    break;
                case 4:
                    queryStudent();
                    break;
                case 5:
                    sortAndPrintStudents();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加学生
    private static void addStudent() {
        System.out.print("请输入学号:");
        String id = scanner.nextLine();
        System.out.print("请输入姓名:");
        String name = scanner.nextLine();
        System.out.print("请输入年龄:");
        int age = scanner.nextInt();
        System.out.print("请输入成绩:");
        double score = scanner.nextDouble();
        scanner.nextLine(); // 消费换行符

        studentList.add(new Student(id, name, age, score));
        System.out.println("学生添加成功!");
    }

    // 删除学生
    private static void deleteStudent() {
        System.out.print("请输入要删除的学生学号:");
        String id = scanner.nextLine();
        for (int i = 0; i < studentList.size(); i++) {
            if (studentList.get(i).getId().equals(id)) {
                studentList.remove(i);
                System.out.println("学生删除成功!");
                return;
            }
        }
        System.out.println("未找到该学号的学生!");
    }

    // 修改学生
    private static void updateStudent() {
        System.out.print("请输入要修改的学生学号:");
        String id = scanner.nextLine();
        for (Student student : studentList) {
            if (student.getId().equals(id)) {
                System.out.print("请输入新姓名(原姓名:" + student.getName() + "):");
                String name = scanner.nextLine();
                System.out.print("请输入新年龄(原年龄:" + student.getAge() + "):");
                int age = scanner.nextInt();
                System.out.print("请输入新成绩(原成绩:" + student.getScore() + "):");
                double score = scanner.nextDouble();
                scanner.nextLine(); // 消费换行符

                student.setName(name);
                student.setAge(age);
                student.setScore(score);
                System.out.println("学生信息修改成功!");
                return;
            }
        }
        System.out.println("未找到该学号的学生!");
    }

    // 查询学生
    private static void queryStudent() {
        System.out.print("请输入要查询的学生学号:");
        String id = scanner.nextLine();
        for (Student student : studentList) {
            if (student.getId().equals(id)) {
                System.out.println(student);
                return;
            }
        }
        System.out.println("未找到该学号的学生!");
    }

    // 排序并输出学生(成绩从高到低)
    private static void sortAndPrintStudents() {
        Collections.sort(studentList, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                // 从高到低,所以用 s2 - s1
                return Double.compare(s2.getScore(), s1.getScore());
            }
        });

        System.out.println("学生信息(成绩从高到低):");
        for (Student student : studentList) {
            System.out.println(student);
        }
    }
}

题目 2:单词统计器(HashMap 应用)

题目描述

编写一个程序,使用 HashMap 统计一段文本中每个单词出现的次数,并输出统计结果。

要求

  • 输入一段文本(例如:“Hello world hello java”)。
  • 使用 HashMap<String, Integer> 存储单词及其出现次数。
  • 输出每个单词及其出现次数(例如:Hello: 2, world: 1, java: 1)。

解答

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一段文本:");
        String text = scanner.nextLine();

        // 分割单词(按非字母数字字符分割,转小写统一格式)
        String[] words = text.toLowerCase().split("[^a-zA-Z0-9]+");

        HashMap<String, Integer> wordCountMap = new HashMap<>();

        // 统计单词次数
        for (String word : words) {
            if (!word.isEmpty()) { // 排除空字符串
                wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
            }
        }

        // 输出结果
        System.out.println("单词统计结果:");
        for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        scanner.close();
    }
}

题目 3:去重与排序(HashSet + TreeSet 应用)

题目描述

给定一个包含重复元素的整数列表,使用 HashSet 去除重复元素,并将去重后的元素按升序排序输出。

要求

  • 使用 ArrayList 存储初始的整数列表。
  • 使用 HashSet 去重。
  • 使用 TreeSetCollections.sort() 对去重后的元素进行升序排序。
  • 输出去重前和去重后的列表。

解答

import java.util.*;

public class RemoveDuplicateAndSort {
    public static void main(String[] args) {
        // 初始列表(包含重复元素)
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(5, 3, 8, 5, 2, 8, 1, 3));

        System.out.println("去重前的列表:" + list);

        // 使用 HashSet 去重
        HashSet<Integer> hashSet = new HashSet<>(list);

        // 转换为 TreeSet 实现升序排序
        TreeSet<Integer> treeSet = new TreeSet<>(hashSet);

        System.out.println("去重并升序排序后的列表:" + treeSet);

        // 或者使用 ArrayList + Collections.sort()
        ArrayList<Integer> sortedList = new ArrayList<>(hashSet);
        Collections.sort(sortedList);
        System.out.println("去重并升序排序后的列表(另一种方式):" + sortedList);
    }
}

题目 4:投票统计系统(HashMap 应用)

题目描述

设计一个投票统计系统,使用 HashMap 统计候选人的得票数,并输出得票最高的候选人。

要求

  • 使用 HashMap<String, Integer> 存储候选人及其得票数。
  • 支持多次投票(通过控制台输入候选人姓名)。
  • 输出所有候选人的得票数,并输出得票最高的候选人。

解答

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class VotingSystem {
    private static HashMap<String, Integer> voteMap = new HashMap<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("===== 投票系统 =====");
        System.out.println("请输入候选人姓名(输入“end”结束投票):");

        while (true) {
            String candidate = scanner.nextLine();
            if (candidate.equalsIgnoreCase("end")) {
                break;
            }
            // 统计票数(不存在则初始化为1,存在则+1)
            voteMap.put(candidate, voteMap.getOrDefault(candidate, 0) + 1);
        }

        // 输出所有候选人得票
        System.out.println("\n投票结果:");
        for (Map.Entry<String, Integer> entry : voteMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue() + "票");
        }

        // 找出得票最高的候选人
        String maxCandidate = null;
        int maxVotes = 0;
        for (Map.Entry<String, Integer> entry : voteMap.entrySet()) {
            if (entry.getValue() > maxVotes) {
                maxVotes = entry.getValue();
                maxCandidate = entry.getKey();
            }
        }
        System.out.println("\n得票最高的候选人是:" + maxCandidate + ",得票数:" + maxVotes);

        scanner.close();
    }
}

题目 5:图书管理系统(ArrayList 应用)

题目描述

设计一个图书管理系统,使用 ArrayList 存储图书信息(包括书名 String、作者 String 和价格 double),并实现以下功能:

  1. 添加图书信息
  2. 删除指定书名的图书信息
  3. 查询某本书的价格
  4. 查询所有图书的平均价格
  5. 按照从低到高的顺序排序并输出图书信息

要求

  • 使用 ArrayList 存储图书对象。
  • 图书信息包括书名(String)、作者(String)和价格(double)。
  • 通过控制台输入输出进行交互。

解答

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

// 图书类
class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    // Getter 和 Setter 方法
    public String getName() { return name; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setName(String name) { this.name = name; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() {
        return "书名:" + name + ",作者:" + author + ",价格:" + price;
    }
}

public class BookManagementSystem {
    private static ArrayList<Book> bookList = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 图书管理系统 =====");
            System.out.println("1. 添加图书");
            System.out.println("2. 删除图书");
            System.out.println("3. 查询图书价格");
            System.out.println("4. 查询图书平均价格");
            System.out.println("5. 排序并输出图书");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addBook();
                    break;
                case 2:
                    deleteBook();
                    break;
                case 3:
                    queryBookPrice();
                    break;
                case 4:
                    queryAveragePrice();
                    break;
                case 5:
                    sortAndPrintBooks();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加图书
    private static void addBook() {
        System.out.print("请输入书名:");
        String name = scanner.nextLine();
        System.out.print("请输入作者:");
        String author = scanner.nextLine();
        System.out.print("请输入价格:");
        double price = scanner.nextDouble();
        scanner.nextLine(); // 消费换行符

        bookList.add(new Book(name, author, price));
        System.out.println("图书添加成功!");
    }

    // 删除图书
    private static void deleteBook() {
        System.out.print("请输入要删除的图书书名:");
        String name = scanner.nextLine();
        for (int i = 0; i < bookList.size(); i++) {
            if (bookList.get(i).getName().equals(name)) {
                bookList.remove(i);
                System.out.println("图书删除成功!");
                return;
            }
        }
        System.out.println("未找到该书名的图书!");
    }

    // 查询图书价格
    private static void queryBookPrice() {
        System.out.print("请输入要查询的图书书名:");
        String name = scanner.nextLine();
        for (Book book : bookList) {
            if (book.getName().equals(name)) {
                System.out.println("《" + book.getName() + "》的价格是:" + book.getPrice());
                return;
            }
        }
        System.out.println("未找到该书名的图书!");
    }

    // 查询图书平均价格
    private static void queryAveragePrice() {
        if (bookList.isEmpty()) {
            System.out.println("没有图书信息!");
            return;
        }
        double totalPrice = 0;
        for (Book book : bookList) {
            totalPrice += book.getPrice();
        }
        double average = totalPrice / bookList.size();
        System.out.println("图书平均价格是:" + average);
    }

    // 排序并输出图书(价格从低到高)
    private static void sortAndPrintBooks() {
        Collections.sort(bookList, new Comparator<Book>() {
            @Override
            public int compare(Book b1, Book b2) {
                // 从低到高,所以用 b1 - b2
                return Double.compare(b1.getPrice(), b2.getPrice());
            }
        });

        System.out.println("图书信息(价格从低到高):");
        for (Book book : bookList) {
            System.out.println(book);
        }
    }
}

题目 6:员工部门管理系统(HashMap + ArrayList 应用)

题目描述

设计一个员工部门管理系统,使用 HashMap<String, ArrayList<String>> 存储部门及其员工列表,并实现以下功能:

  1. 添加部门及员工
  2. 按照部门名称检索该部门的所有员工
  3. 删除某个部门
  4. 统计每个部门的员工数量
  5. 输出所有部门及其员工信息

要求

  • 使用 HashMap<String, ArrayList<String>> 存储“部门名称-员工列表”的映射。
  • 部门名称和员工均为字符串类型。
  • 通过控制台输入输出进行交互。

解答

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class DepartmentEmployeeSystem {
    private static HashMap<String, ArrayList<String>> deptEmpMap = new HashMap<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 员工部门管理系统 =====");
            System.out.println("1. 添加部门及员工");
            System.out.println("2. 按部门检索员工");
            System.out.println("3. 删除部门");
            System.out.println("4. 统计部门员工数量");
            System.out.println("5. 输出所有部门及员工");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addDeptAndEmployee();
                    break;
                case 2:
                    queryEmployeesByDept();
                    break;
                case 3:
                    deleteDepartment();
                    break;
                case 4:
                    countEmployeesInDept();
                    break;
                case 5:
                    printAllDeptAndEmployees();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加部门及员工
    private static void addDeptAndEmployee() {
        System.out.print("请输入部门名称:");
        String dept = scanner.nextLine();
        System.out.print("请输入员工姓名:");
        String emp = scanner.nextLine();

        if (!deptEmpMap.containsKey(dept)) {
            deptEmpMap.put(dept, new ArrayList<>());
        }
        deptEmpMap.get(dept).add(emp);
        System.out.println("部门及员工添加成功!");
    }

    // 按部门检索员工
    private static void queryEmployeesByDept() {
        System.out.print("请输入要检索的部门名称:");
        String dept = scanner.nextLine();
        if (deptEmpMap.containsKey(dept)) {
            System.out.println(dept + " 部门的员工:" + deptEmpMap.get(dept));
        } else {
            System.out.println("未找到该部门!");
        }
    }

    // 删除部门
    private static void deleteDepartment() {
        System.out.print("请输入要删除的部门名称:");
        String dept = scanner.nextLine();
        if (deptEmpMap.containsKey(dept)) {
            deptEmpMap.remove(dept);
            System.out.println("部门删除成功!");
        } else {
            System.out.println("未找到该部门!");
        }
    }

    // 统计部门员工数量
    private static void countEmployeesInDept() {
        System.out.print("请输入要统计的部门名称:");
        String dept = scanner.nextLine();
        if (deptEmpMap.containsKey(dept)) {
            int count = deptEmpMap.get(dept).size();
            System.out.println(dept + " 部门的员工数量:" + count);
        } else {
            System.out.println("未找到该部门!");
        }
    }

    // 输出所有部门及员工
    private static void printAllDeptAndEmployees() {
        System.out.println("所有部门及员工信息:");
        for (Map.Entry<String, ArrayList<String>> entry : deptEmpMap.entrySet()) {
            System.out.println(entry.getKey() + " 部门:" + entry.getValue());
        }
    }
}

题目 7:商品库存管理系统(ArrayList 应用)

题目描述

设计一个商品库存管理系统,使用 ArrayList 存储商品信息(包含商品编号 String、名称 String、价格 double 和库存数 int),并实现以下功能:

  1. 添加商品信息
  2. 按照商品编号查询商品信息
  3. 更新商品的库存数量
  4. 输出库存数量大于某个阈值的商品
  5. 按照从低到高的顺序排序并输出商品信息

要求

  • 使用 ArrayList 存储商品对象。
  • 商品信息包含编号、名称、价格和库存数。
  • 通过控制台输入输出进行交互。

解答

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

// 商品类
class Product {
    private String id;
    private String name;
    private double price;
    private int stock;

    public Product(String id, String name, double price, int stock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    // Getter 和 Setter 方法
    public String getId() { return id; }
    public String getName() { return name; }
    public double getPrice() { return price; }
    public int getStock() { return stock; }
    public void setStock(int stock) { this.stock = stock; }

    @Override
    public String toString() {
        return "编号:" + id + ",名称:" + name + ",价格:" + price + ",库存:" + stock;
    }
}

public class ProductInventorySystem {
    private static ArrayList<Product> productList = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 商品库存管理系统 =====");
            System.out.println("1. 添加商品");
            System.out.println("2. 按编号查询商品");
            System.out.println("3. 更新商品库存");
            System.out.println("4. 输出库存大于阈值的商品");
            System.out.println("5. 按价格排序输出商品");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addProduct();
                    break;
                case 2:
                    queryProductById();
                    break;
                case 3:
                    updateProductStock();
                    break;
                case 4:
                    printProductsWithStockAboveThreshold();
                    break;
                case 5:
                    sortAndPrintProductsByPrice();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加商品
    private static void addProduct() {
        System.out.print("请输入商品编号:");
        String id = scanner.nextLine();
        System.out.print("请输入商品名称:");
        String name = scanner.nextLine();
        System.out.print("请输入商品价格:");
        double price = scanner.nextDouble();
        System.out.print("请输入商品库存:");
        int stock = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        productList.add(new Product(id, name, price, stock));
        System.out.println("商品添加成功!");
    }

    // 按编号查询商品
    private static void queryProductById() {
        System.out.print("请输入要查询的商品编号:");
        String id = scanner.nextLine();
        for (Product product : productList) {
            if (product.getId().equals(id)) {
                System.out.println(product);
                return;
            }
        }
        System.out.println("未找到该编号的商品!");
    }

    // 更新商品库存
    private static void updateProductStock() {
        System.out.print("请输入要更新的商品编号:");
        String id = scanner.nextLine();
        for (Product product : productList) {
            if (product.getId().equals(id)) {
                System.out.print("请输入新库存(原库存:" + product.getStock() + "):");
                int stock = scanner.nextInt();
                scanner.nextLine(); // 消费换行符
                product.setStock(stock);
                System.out.println("商品库存更新成功!");
                return;
            }
        }
        System.out.println("未找到该编号的商品!");
    }

    // 输出库存大于阈值的商品
    private static void printProductsWithStockAboveThreshold() {
        System.out.print("请输入库存阈值:");
        int threshold = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        System.out.println("库存大于" + threshold + "的商品:");
        for (Product product : productList) {
            if (product.getStock() > threshold) {
                System.out.println(product);
            }
        }
    }

    // 按价格排序输出商品(从低到高)
    private static void sortAndPrintProductsByPrice() {
        Collections.sort(productList, new Comparator<Product>() {
            @Override
            public int compare(Product p1, Product p2) {
                return Double.compare(p1.getPrice(), p2.getPrice());
            }
        });

        System.out.println("商品按价格从低到高排序:");
        for (Product product : productList) {
            System.out.println(product);
        }
    }
}

题目 8:课程选修系统(HashMap + ArrayList 应用)

题目描述

设计一个课程选修系统,使用 HashMap<String, ArrayList<String>> 存储学生及其选修的课程列表,并实现以下功能:

  1. 添加学生及选修的课程
  2. 按照学生姓名检索其选修的课程
  3. 删除某个学生的选课记录
  4. 统计每门课程的选课人数
  5. 输出所有学生及其选课信息

要求

  • 使用 HashMap<String, ArrayList<String>> 存储“学生姓名-课程列表”的映射。
  • 学生姓名和课程均为字符串类型。
  • 通过控制台输入输出进行交互。

解答

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CourseSelectionSystem {
    private static HashMap<String, ArrayList<String>> studentCourseMap = new HashMap<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 课程选修系统 =====");
            System.out.println("1. 添加学生及选课");
            System.out.println("2. 按学生检索课程");
            System.out.println("3. 删除学生选课记录");
            System.out.println("4. 统计课程选课人数");
            System.out.println("5. 输出所有学生及选课");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addStudentAndCourse();
                    break;
                case 2:
                    queryCoursesByStudent();
                    break;
                case 3:
                    deleteStudentCourseRecord();
                    break;
                case 4:
                    countCourseSelection();
                    break;
                case 5:
                    printAllStudentAndCourses();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加学生及选课
    private static void addStudentAndCourse() {
        System.out.print("请输入学生姓名:");
        String student = scanner.nextLine();
        System.out.print("请输入课程名称:");
        String course = scanner.nextLine();

        if (!studentCourseMap.containsKey(student)) {
            studentCourseMap.put(student, new ArrayList<>());
        }
        studentCourseMap.get(student).add(course);
        System.out.println("学生选课添加成功!");
    }

    // 按学生检索课程
    private static void queryCoursesByStudent() {
        System.out.print("请输入要检索的学生姓名:");
        String student = scanner.nextLine();
        if (studentCourseMap.containsKey(student)) {
            System.out.println(student + " 选修的课程:" + studentCourseMap.get(student));
        } else {
            System.out.println("未找到该学生!");
        }
    }

    // 删除学生选课记录
    private static void deleteStudentCourseRecord() {
        System.out.print("请输入要删除选课记录的学生姓名:");
        String student = scanner.nextLine();
        if (studentCourseMap.containsKey(student)) {
            studentCourseMap.remove(student);
            System.out.println("学生选课记录删除成功!");
        } else {
            System.out.println("未找到该学生!");
        }
    }

    // 统计课程选课人数
    private static void countCourseSelection() {
        HashMap<String, Integer> courseCountMap = new HashMap<>();
        for (ArrayList<String> courses : studentCourseMap.values()) {
            for (String course : courses) {
                courseCountMap.put(course, courseCountMap.getOrDefault(course, 0) + 1);
            }
        }

        System.out.println("课程选课人数统计:");
        for (Map.Entry<String, Integer> entry : courseCountMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue() + "人");
        }
    }

    // 输出所有学生及选课
    private static void printAllStudentAndCourses() {
        System.out.println("所有学生及选课信息:");
        for (Map.Entry<String, ArrayList<String>> entry : studentCourseMap.entrySet()) {
            System.out.println(entry.getKey() + " 选修的课程:" + entry.getValue());
        }
    }
}

题目 9:音乐播放列表管理系统(LinkedList 应用)

题目描述

设计一个音乐播放列表管理系统,使用 LinkedList 存储歌曲名称,并实现以下功能:

  1. 添加歌曲到播放列表
  2. 移除播放列表中的指定歌曲
  3. 随机播放列表中的任意歌曲
  4. 输出当前播放列表中的所有歌曲
  5. 实现上一首/下一首功能,模拟播放器的切换歌曲操作

要求

  • 使用 LinkedList<String> 存储歌曲名称。
  • 使用 LinkedList 的特性(双向遍历)实现上一首/下一首功能。
  • 通过控制台输入输出进行交互。

解答

import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;

public class MusicPlaylistSystem {
    private static LinkedList<String> playlist = new LinkedList<>();
    private static int currentIndex = -1; // 当前播放歌曲的索引,-1表示无播放
    private static Scanner scanner = new Scanner(System.in);
    private static Random random = new Random();

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 音乐播放列表管理系统 =====");
            System.out.println("1. 添加歌曲");
            System.out.println("2. 移除歌曲");
            System.out.println("3. 随机播放歌曲");
            System.out.println("4. 输出所有歌曲");
            System.out.println("5. 上一首");
            System.out.println("6. 下一首");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addSong();
                    break;
                case 2:
                    removeSong();
                    break;
                case 3:
                    playRandomSong();
                    break;
                case 4:
                    printAllSongs();
                    break;
                case 5:
                    playPreviousSong();
                    break;
                case 6:
                    playNextSong();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加歌曲
    private static void addSong() {
        System.out.print("请输入歌曲名称:");
        String song = scanner.nextLine();
        playlist.add(song);
        System.out.println("歌曲添加成功!");
    }

    // 移除歌曲
    private static void removeSong() {
        System.out.print("请输入要移除的歌曲名称:");
        String song = scanner.nextLine();
        if (playlist.remove(song)) {
            // 如果移除的是当前播放的歌曲,重置索引
            if (currentIndex != -1 && playlist.size() < currentIndex + 1) {
                currentIndex = -1;
            }
            System.out.println("歌曲移除成功!");
        } else {
            System.out.println("未找到该歌曲!");
        }
    }

    // 随机播放歌曲
    private static void playRandomSong() {
        if (playlist.isEmpty()) {
            System.out.println("播放列表为空!");
            return;
        }
        currentIndex = random.nextInt(playlist.size());
        System.out.println("正在播放:" + playlist.get(currentIndex));
    }

    // 输出所有歌曲
    private static void printAllSongs() {
        System.out.println("播放列表中的歌曲:");
        for (int i = 0; i < playlist.size(); i++) {
            String status = (currentIndex == i) ? " [当前播放]" : "";
            System.out.println((i + 1) + ". " + playlist.get(i) + status);
        }
    }

    // 上一首
    private static void playPreviousSong() {
        if (playlist.isEmpty()) {
            System.out.println("播放列表为空!");
            return;
        }
        if (currentIndex == -1) {
            currentIndex = 0;
        } else {
            currentIndex = (currentIndex - 1 + playlist.size()) % playlist.size();
        }
        System.out.println("正在播放:" + playlist.get(currentIndex));
    }

    // 下一首
    private static void playNextSong() {
        if (playlist.isEmpty()) {
            System.out.println("播放列表为空!");
            return;
        }
        if (currentIndex == -1) {
            currentIndex = 0;
        } else {
            currentIndex = (currentIndex + 1) % playlist.size();
        }
        System.out.println("正在播放:" + playlist.get(currentIndex));
    }
}

题目 10:城市天气统计系统(HashMap 应用)

题目描述

设计一个城市天气统计系统,使用 HashMap<String, Weather> 存储城市及其天气信息(包括温度 double 和天气状况 String),并实现以下功能:

  1. 添加城市及其天气信息
  2. 按照城市名称检索天气信息
  3. 删除某个城市的天气信息
  4. 输出温度最高的城市及其天气信息
  5. 输出所有城市及其天气信息

要求

  • 使用 HashMap<String, Weather> 存储“城市名称-天气对象”的映射。
  • 天气信息包含温度和天气状况。
  • 通过控制台输入输出进行交互。

解答

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 天气类
class Weather {
    private double temperature;
    private String condition;

    public Weather(double temperature, String condition) {
        this.temperature = temperature;
        this.condition = condition;
    }

    // Getter 方法
    public double getTemperature() { return temperature; }
    public String getCondition() { return condition; }

    @Override
    public String toString() {
        return "温度:" + temperature + "℃,天气:" + condition;
    }
}

public class CityWeatherSystem {
    private static HashMap<String, Weather> cityWeatherMap = new HashMap<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            System.out.println("===== 城市天气统计系统 =====");
            System.out.println("1. 添加城市天气");
            System.out.println("2. 按城市检索天气");
            System.out.println("3. 删除城市天气");
            System.out.println("4. 输出温度最高的城市天气");
            System.out.println("5. 输出所有城市天气");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作:");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            switch (choice) {
                case 1:
                    addCityWeather();
                    break;
                case 2:
                    queryCityWeather();
                    break;
                case 3:
                    deleteCityWeather();
                    break;
                case 4:
                    printCityWithHighestTemperature();
                    break;
                case 5:
                    printAllCityWeather();
                    break;
                case 0:
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("输入有误,请重新选择!");
            }
        }
    }

    // 添加城市天气
    private static void addCityWeather() {
        System.out.print("请输入城市名称:");
        String city = scanner.nextLine();
        System.out.print("请输入温度:");
        double temperature = scanner.nextDouble();
        System.out.print("请输入天气状况:");
        scanner.nextLine(); // 消费换行符
        String condition = scanner.nextLine();

        cityWeatherMap.put(city, new Weather(temperature, condition));
        System.out.println("城市天气添加成功!");
    }

    // 按城市检索天气
    private static void queryCityWeather() {
        System.out.print("请输入要检索的城市名称:");
        String city = scanner.nextLine();
        if (cityWeatherMap.containsKey(city)) {
            System.out.println(city + " 的天气:" + cityWeatherMap.get(city));
        } else {
            System.out.println("未找到该城市的天气信息!");
        }
    }

    // 删除城市天气
    private static void deleteCityWeather() {
        System.out.print("请输入要删除的城市名称:");
        String city = scanner.nextLine();
        if (cityWeatherMap.containsKey(city)) {
            cityWeatherMap.remove(city);
            System.out.println("城市天气信息删除成功!");
        } else {
            System.out.println("未找到该城市的天气信息!");
        }
    }

    // 输出温度最高的城市天气
    private static void printCityWithHighestTemperature() {
        if (cityWeatherMap.isEmpty()) {
            System.out.println("没有城市天气信息!");
            return;
        }
        String maxCity = null;
        double maxTemp = -Double.MAX_VALUE;
        for (Map.Entry<String, Weather> entry : cityWeatherMap.entrySet()) {
            if (entry.getValue().getTemperature() > maxTemp) {
                maxTemp = entry.getValue().getTemperature();
                maxCity = entry.getKey();
            }
        }
        System.out.println("温度最高的城市:" + maxCity + ",天气:" + cityWeatherMap.get(maxCity));
    }

    // 输出所有城市天气
    private static void printAllCityWeather() {
        System.out.println("所有城市天气信息:");
        for (Map.Entry<String, Weather> entry : cityWeatherMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐