21xrx.com
2024-11-08 21:59:30 Friday
登录
文章检索 我的文章 写文章
题目及代码
2023-06-15 12:39:25 深夜i     --     --
Java课程设计 题目 代码

Java编程语言已经成为计算机科学教育中不可或缺的一部分,因为它在编写高性能、可靠和安全的应用程序方面得到了广泛的应用。为了帮助学生更好地掌握Java编程语言,教师总是会布置设计Java程序的题目。在这篇文章中,我们将介绍几个Java课程设计题目,并提供相应的代码。

1. 简单的计算器

这个题目要求学生使用Java编写一个简单的计算器,可以执行加、减、乘、除等基本算术运算。在实现这个计算器时,学生需要使用Java GUI(图形用户界面)库来创建用户界面。下面是一个基本的Java计算器代码:


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {

  private static final long serialVersionUID = 1L;

  private JTextField displayField;

  private JButton zeroButton, oneButton, twoButton, threeButton, fourButton, fiveButton, sixButton, sevenButton, eightButton, nineButton;

  private JButton addButton, subtractButton, multiplyButton, divideButton, equalsButton, decimalButton, clearButton;

  private double firstNum = 0;

  private double secondNum = 0;

  private String operator = "";

  private boolean isFirstNum = true;

  private boolean isSecondNum = false;

  private boolean isDecimalPoint = false;

  public Calculator() {

    super("Calculator");

    Container contentPane = getContentPane();

    contentPane.setLayout(new BorderLayout());

    displayField = new JTextField("0", 30);

    contentPane.add(displayField, BorderLayout.NORTH);

    JPanel centerPanel = new JPanel();

    centerPanel.setLayout(new GridLayout(4, 4));

    // Create number buttons

    zeroButton = new JButton("0");

    zeroButton.addActionListener(this);

    centerPanel.add(zeroButton);

    oneButton = new JButton("1");

    oneButton.addActionListener(this);

    centerPanel.add(oneButton);

    twoButton = new JButton("2");

    twoButton.addActionListener(this);

    centerPanel.add(twoButton);

    threeButton = new JButton("3");

    threeButton.addActionListener(this);

    centerPanel.add(threeButton);

    fourButton = new JButton("4");

    fourButton.addActionListener(this);

    centerPanel.add(fourButton);

    fiveButton = new JButton("5");

    fiveButton.addActionListener(this);

    centerPanel.add(fiveButton);

    sixButton = new JButton("6");

    sixButton.addActionListener(this);

    centerPanel.add(sixButton);

    sevenButton = new JButton("7");

    sevenButton.addActionListener(this);

    centerPanel.add(sevenButton);

    eightButton = new JButton("8");

    eightButton.addActionListener(this);

    centerPanel.add(eightButton);

    nineButton = new JButton("9");

    nineButton.addActionListener(this);

    centerPanel.add(nineButton);

    // Create operator buttons

    addButton = new JButton("+");

    addButton.addActionListener(this);

    centerPanel.add(addButton);

    subtractButton = new JButton("-");

    subtractButton.addActionListener(this);

    centerPanel.add(subtractButton);

    multiplyButton = new JButton("*");

    multiplyButton.addActionListener(this);

    centerPanel.add(multiplyButton);

    divideButton = new JButton("/");

    divideButton.addActionListener(this);

    centerPanel.add(divideButton);

    equalsButton = new JButton("=");

    equalsButton.addActionListener(this);

    centerPanel.add(equalsButton);

    decimalButton = new JButton(".");

    decimalButton.addActionListener(this);

    centerPanel.add(decimalButton);

    clearButton = new JButton("C");

    clearButton.addActionListener(this);

    centerPanel.add(clearButton);

    contentPane.add(centerPanel, BorderLayout.CENTER);

  }

  public static void main(String[] args) {

    Calculator calculator = new Calculator();

    calculator.setSize(300, 250);

    calculator.setVisible(true);

  }

  // Event handler method for button clicks

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == zeroButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "0");

      } else {

        processNumberInput("0");

      }

    } else if (e.getSource() == oneButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "1");

      } else {

        processNumberInput("1");

      }

    } else if (e.getSource() == twoButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "2");

      } else {

        processNumberInput("2");

      }

    } else if (e.getSource() == threeButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "3");

      } else {

        processNumberInput("3");

      }

    } else if (e.getSource() == fourButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "4");

      } else {

        processNumberInput("4");

      }

    } else if (e.getSource() == fiveButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "5");

      } else {

        processNumberInput("5");

      }

    } else if (e.getSource() == sixButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "6");

      } else {

        processNumberInput("6");

      }

    } else if (e.getSource() == sevenButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "7");

      } else {

        processNumberInput("7");

      }

    } else if (e.getSource() == eightButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "8");

      } else {

        processNumberInput("8");

      }

    } else if (e.getSource() == nineButton) {

      if (isDecimalPoint) {

        displayField.setText(displayField.getText() + "9");

      } else {

        processNumberInput("9");

      }

    } else if (e.getSource() == decimalButton) {

      isDecimalPoint = true;

      displayField.setText(displayField.getText() + ".");

    } else if (e.getSource() == clearButton) {

      displayField.setText("0");

      firstNum = 0;

      secondNum = 0;

      operator = "";

      isFirstNum = true;

      isSecondNum = false;

      isDecimalPoint = false;

    } else if (e.getSource() == addButton) {

      isFirstNum = false;

      isSecondNum = true;

      operator = "+";

      firstNum = Double.parseDouble(displayField.getText());

    } else if (e.getSource() == subtractButton) {

      isFirstNum = false;

      isSecondNum = true;

      operator = "-";

      firstNum = Double.parseDouble(displayField.getText());

    } else if (e.getSource() == multiplyButton) {

      isFirstNum = false;

      isSecondNum = true;

      operator = "*";

      firstNum = Double.parseDouble(displayField.getText());

    } else if (e.getSource() == divideButton) {

      isFirstNum = false;

      isSecondNum = true;

      operator = "/";

      firstNum = Double.parseDouble(displayField.getText());

    } else if (e.getSource() == equalsButton) {

      if (isSecondNum) {

        secondNum = Double.parseDouble(displayField.getText());

      } else

        secondNum = firstNum;

      

      switch (operator) {

        case "+":

          firstNum = firstNum + secondNum;

          break;

        case "-":

          firstNum = firstNum - secondNum;

          break;

        case "*":

          firstNum = firstNum * secondNum;

          break;

        case "/":

          if (secondNum != 0)

            firstNum = firstNum / secondNum;

           else {

            displayField.setText("Error: Division by zero");

          }

          break;

      }

      if (operator.equals("/") && secondNum == 0) {

        displayField.setText("Error: Division by zero");

        firstNum = 0;

      } else {

        String result = String.format("%.2f", firstNum);

        displayField.setText(result);

      }

      isFirstNum = true;

      isSecondNum = false;

      isDecimalPoint = false;

    }

  }

  // Helper method to process number input from user

  private void processNumberInput(String key) {

    if (isFirstNum) {

      displayField.setText(key);

    } else if (isSecondNum) {

      displayField.setText(key);

      isSecondNum = false;

    } else {

      displayField.setText(displayField.getText() + key);

    }

  }

}

这段代码使用Java Swing库创建了一个简单的计算器界面,可以执行四种基本算术运算,以及清除操作。在计算过程中,程序会在界面上显示数字和运算符,并在计算完成后输出结果。

2. 学生管理系统

这个题目要求学生使用Java编写一个学生管理系统,可以添加、删除和修改学生的信息,包括姓名、学号、成绩等。为了实现这个学生管理系统,学生需要使用Java GUI和数据库编程技术。下面是一个基本的Java学生管理系统的代码:


import javax.swing.*;

import javax.swing.border.EmptyBorder;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.sql.*;

public class StudentManagementSystem extends JFrame implements ActionListener {

  private static final long serialVersionUID = 1L;

  private JTextField nameField, idField, scoreField;

  private JButton addButton, deleteButton, updateButton, searchButton, clearButton;

  private JTable table;

  private DefaultTableModel model;

  private Connection conn;

  private Statement stmt;

  public StudentManagementSystem() {

    super("Student Management System");

    Container contentPane = getContentPane();

    contentPane.setLayout(new BorderLayout());

    JPanel topPanel = new JPanel();

    topPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

    topPanel.setLayout(new GridLayout(2, 3, 10, 10));

    JLabel nameLabel = new JLabel("Name:");

    nameField = new JTextField();

    topPanel.add(nameLabel);

    topPanel.add(nameField);

    JLabel idLabel = new JLabel("ID:");

    idField = new JTextField();

    topPanel.add(idLabel);

    topPanel.add(idField);

    JLabel scoreLabel = new JLabel("Score:");

    scoreField = new JTextField();

    topPanel.add(scoreLabel);

    topPanel.add(scoreField);

    contentPane.add(topPanel, BorderLayout.NORTH);

    JPanel centerPanel = new JPanel();

    centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

    centerPanel.setLayout(new BorderLayout());

    model = new DefaultTableModel();

    model.addColumn("ID");

    model.addColumn("Name");

    model.addColumn("Score");

    table = new JTable(model);

    JScrollPane scrollPane = new JScrollPane(table);

    centerPanel.add(scrollPane, BorderLayout.CENTER);

    contentPane.add(centerPanel, BorderLayout.CENTER);

    JPanel bottomPanel = new JPanel();

    bottomPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

    bottomPanel.setLayout(new GridLayout(1, 5, 10, 10));

    addButton = new JButton("Add");

    addButton.addActionListener(this);

    bottomPanel.add(addButton);

    deleteButton = new JButton("Delete");

    deleteButton.addActionListener(this);

    bottomPanel.add(deleteButton);

    updateButton = new JButton("Update");

    updateButton.addActionListener(this);

    bottomPanel.add(updateButton);

    searchButton = new JButton("Search");

    searchButton.addActionListener(this);

    bottomPanel.add(searchButton);

    clearButton = new JButton("Clear");

    clearButton.addActionListener(this);

    bottomPanel.add(clearButton);

    contentPane.add(bottomPanel, BorderLayout.SOUTH);

    setSize(500, 400);

    setVisible(true);

    // Establish connection with SQLite database

    try {

      Class.forName("org.sqlite.JDBC");

      conn = DriverManager.getConnection("jdbc:sqlite:students.db");

      stmt = conn.createStatement();

      stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Students (id INTEGER PRIMARY KEY, name TEXT, score REAL)");

    } catch (ClassNotFoundException | SQLException e) {

      e.printStackTrace();

    }

  }

  public static void main(String[] args) {

    new StudentManagementSystem();

  }

  // Event handler method for button clicks

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == addButton) {

      String name = nameField.getText();

      String id = idField.getText();

      String score = scoreField.getText();

      if (name.isEmpty() || id.isEmpty() || score.isEmpty()) {

        JOptionPane.showMessageDialog(this, "Please enter all fields", "Error", JOptionPane.ERROR_MESSAGE);

      } else {

        try {

          String insertQuery = "INSERT INTO Students (id, name, score) VALUES (" + id + ", '" + name + "', " + score + ")";

          stmt.executeUpdate(insertQuery);

          model.addRow(new Object[]id);

          nameField.setText("");

          idField.setText("");

          scoreField.setText("");

        } catch (SQLException ex) {

          ex.printStackTrace();

        }

      }

    } else if (e.getSource() == deleteButton) {

      int row = table.getSelectedRow();

      if (row == -1) {

        JOptionPane.showMessageDialog(this, "Please select a row to delete", "Error", JOptionPane.ERROR_MESSAGE);

      } else {

        String id = model.getValueAt(row, 0).toString();

        try {

          String deleteQuery = "DELETE FROM Students WHERE id=" + id;

          stmt.executeUpdate(deleteQuery);

          model.removeRow(row);

        } catch (SQLException ex) {

          ex.printStackTrace();

        }

      }

    } else if (e.getSource() == updateButton) {

      int row = table.getSelectedRow();

      if (row == -1) {

        JOptionPane.showMessageDialog(this, "Please select a row to update", "Error", JOptionPane.ERROR_MESSAGE);

      } else {

        String id = model.getValueAt(row, 0).toString();

        String name = nameField.getText();

        String score = scoreField.getText();

        if (name.isEmpty() || score.isEmpty()) {

          JOptionPane.showMessageDialog(this, "Please enter name and score", "Error", JOptionPane.ERROR_MESSAGE);

        } else {

          try {

            String updateQuery = "UPDATE Students SET name='" + name + "', score=" + score + " WHERE id=" + id;

            stmt.executeUpdate(updateQuery);

            model.setValueAt(name, row, 1);

            model.setValueAt(score, row, 2);

            nameField.setText("");

            idField.setText("");

            scoreField.setText("");

          } catch (SQLException ex) {

            ex.printStackTrace();

          }

        }

      }

    } else if (e.getSource() == searchButton) {

      String id = idField.getText();

      if (!id.isEmpty()) {

        try {

          String searchQuery = "SELECT * FROM Students WHERE id=" + id;

          ResultSet rs = stmt.executeQuery(searchQuery);

          if (rs.next()) {

            String name = rs.getString("name");

            String score = String.valueOf(rs.getDouble("score"));

            nameField.setText(name);

            scoreField.setText(score);

          } else {

            JOptionPane.showMessageDialog(this, "No match found", "Error", JOptionPane.ERROR_MESSAGE);

          }

        } catch (SQLException ex) {

          ex.printStackTrace();

        }

      } else {

        JOptionPane.showMessageDialog(this, "Please enter ID", "Error", JOptionPane.ERROR_MESSAGE);

      }

    } else if (e.getSource() == clearButton) {

      nameField.setText("");

      idField.setText("");

      scoreField.setText("");

    }

  }

  // Close database connection when the window is closed

  public void windowClosing(WindowEvent e) {

    try {

      stmt.close();

      conn.close();

    } catch (SQLException ex) {

      ex.printStackTrace();

    }

    System.exit(0);

  }

}

这段代码使用Java Swing和JDBC(Java数据库连接)库创建了一个学生管理系统的界面,并与SQLite数据库进行交互来存储和检索学生信息。学生可以添加、删除、更新和搜索学生记录,并可以在界面上查看所有学生记录。

3. 飞机大战游戏

这个题目要求学生使用Java编写一个飞机大战游戏,类似于经典的街机游戏1942。在游戏中,玩家将操纵一个战斗机,击败敌人和Boss,赚取分数并进入下一关。为了实现这个游戏,学生需要使用Java Swing和多线程编程技术。下面是一个基本的Java飞机大战游戏的代码:

```java

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.ArrayList;

import java.util.Random;

public class PlaneGame extends JFrame implements KeyListener, ActionListener, Runnable {

  private static final long serialVersionUID = 1L;

  private Image backgroundImage;

  private Image explodeImage;

  private Image playerImage;

  private Image enemyImage;

  private Image bossImage;

  private Image bossBulletImage;

  private Image playerBulletImage;

  private ArrayList enemyPlanes;

  private ArrayList bossPlanes;

  private ArrayList playerBullets;

  private ArrayList bossBullets;

  private PlayerPlane player;

  private BossPlane boss;

  private boolean isRunning;

  private boolean isGameOver;

  private int score;

  private int level;

  private int playerHealth;

  private int bossHealth;

  private Random random;

  public PlaneGame() {

    super("Plane Game");

    addKeyListener(this);

    setSize(600, 800);

    setVisible(true);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setResizable(false);

    isRunning = false;

    isGameOver = false;

    backgroundImage = new ImageIcon("background.jpg").getImage();

    explodeImage = new ImageIcon("explode.png").getImage();

    playerImage = new ImageIcon("player.png").getImage();

    enemyImage = new ImageIcon("enemy.png").getImage();

    bossImage = new ImageIcon("boss.png").getImage();

    bossBulletImage = new ImageIcon("boss_bullet.png").getImage();

    playerBulletImage = new ImageIcon("player_bullet.png").getImage();

    random = new Random();

  }

  public static void main(String[] args) {

    PlaneGame game = new

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复