21xrx.com
2024-11-22 14:10:39 Friday
登录
文章检索 我的文章 写文章
Java程序设计初学者必看的5个案例
2023-06-15 07:13:38 深夜i     --     --
Java Swing库

在学习Java程序设计的过程中,初学者经常会遇到各种各样的问题,比如说如何用Java实现一个简单的计算器、如何用Java制作一个登录界面等。本文将为初学者们提供5个实用案例,帮助他们快速入门Java程序设计。

1. 简易计算器

本案例通过Java Swing库实现了一个简单的计算器程序。该程序支持加、减、乘、除四种基本算术运算,并且支持连续计算。

代码实现:


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Calculator extends JFrame {

  public static void main(String[] args) {

    Calculator calculator = new Calculator();

  }

  private JTextField inputField = new JTextField();//用于输入的文本框

  private double result = 0;

  private String operator = "+";

  private boolean firstInput = true;

  public Calculator() {

    super("计算器");

    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    JPanel panel = (JPanel) getContentPane();

    panel.setLayout(new BorderLayout());

    JPanel inputPanel = new JPanel();

    inputPanel.setLayout(new BorderLayout());

    inputPanel.add(inputField, BorderLayout.CENTER);

    inputField.setHorizontalAlignment(JTextField.RIGHT);

    inputField.setFont(new Font("宋体", Font.PLAIN, 20));

    panel.add(inputPanel, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel();

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

    String[] buttonNames = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};

    for (String name : buttonNames) {

      JButton button = new JButton(name);

      button.setFont(new Font("宋体", Font.PLAIN, 20));

      button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {

          if (name.matches("[0-9]")) {

            inputNumber(name);

          } else if (name.equals(".")) {

            inputDot();

          } else if (name.equals("=")) {

            calculate();

          } else {

            setOperator(name);

          }

        }

      });

      buttonPanel.add(button);

    }

    panel.add(buttonPanel, BorderLayout.CENTER);

    pack();

    setVisible(true);

  }

  private void inputNumber(String number) {

    if (firstInput) {

      inputField.setText(number);

      firstInput = false;

    } else if (inputField.getText().equals("0")) {

      inputField.setText(number);

    } else {

      inputField.setText(inputField.getText() + number);

    }

  }

  private void inputDot() {

    if (firstInput) {

      inputField.setText("0.");

      firstInput = false;

    } else if (inputField.getText().indexOf(".") == -1) {

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

    }

  }

  private void setOperator(String operator) {

    if (this.operator.equals("+")) {

      result += Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("-")) {

      result -= Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("*")) {

      result *= Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("/")) {

      result /= Double.parseDouble(inputField.getText());

    }

    inputField.setText("");

    this.operator = operator;

  }

  private void calculate() {

    if (this.operator.equals("+")) {

      result += Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("-")) {

      result -= Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("*")) {

      result *= Double.parseDouble(inputField.getText());

    } else if (this.operator.equals("/")) {

      result /= Double.parseDouble(inputField.getText());

    }

    inputField.setText(Double.toString(result));

    this.operator = "+";

    result = 0;

    firstInput = true;

  }

}

2. 圆周率计算

本案例通过蒙特卡洛算法计算了圆周率的近似值。算法的原理为,在正方形内部随机撒点,然后统计落在圆内的点数与总点数的比值,将这个比值乘以4,就可以得到圆周率的近似值。

代码实现:


public class PiCalculation {

  public static void main(String[] args) {

    int total = 100000;//总点数

    int count = 0;//在圆内的点数

    for (int i = 0; i < total; i++) {

      double x = Math.random();

      double y = Math.random();

      if (x * x + y * y <= 1) {

        count++;

      }

    }

    double pi = count * 4.0 / total;

    System.out.println("π的近似值为:" + pi);

  }

}

3. 温度转换器

本案例通过Java Swing库实现了一个摄氏度与华氏度之间的转换器,用户可以输入摄氏度或华氏度的数值,程序会自动计算出转换后的结果。

代码实现:


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TemperatureConverter extends JFrame {

  public static void main(String[] args) {

    TemperatureConverter converter = new TemperatureConverter();

  }

  private JTextField inputField = new JTextField();

  private JTextField resultField = new JTextField();

  private JRadioButton celsiusButton = new JRadioButton("摄氏度");

  private JRadioButton fahrenheitButton = new JRadioButton("华氏度");

  public TemperatureConverter() {

    super("温度转换器");

    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    JPanel panel = (JPanel) getContentPane();

    panel.setLayout(new BorderLayout());

    JPanel inputPanel = new JPanel();

    inputPanel.setLayout(new BorderLayout());

    inputPanel.add(inputField, BorderLayout.CENTER);

    inputField.setHorizontalAlignment(JTextField.RIGHT);

    inputField.setFont(new Font("宋体", Font.PLAIN, 20));

    panel.add(inputPanel, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel();

    buttonPanel.setLayout(new GridLayout(1, 2));

    buttonPanel.add(celsiusButton);

    buttonPanel.add(fahrenheitButton);

    ButtonGroup group = new ButtonGroup();

    group.add(celsiusButton);

    group.add(fahrenheitButton);

    celsiusButton.setSelected(true);

    panel.add(buttonPanel, BorderLayout.CENTER);

    JPanel resultPanel = new JPanel();

    resultPanel.setLayout(new BorderLayout());

    resultPanel.add(resultField, BorderLayout.CENTER);

    resultField.setHorizontalAlignment(JTextField.RIGHT);

    resultField.setFont(new Font("宋体", Font.PLAIN, 20));

    resultField.setEditable(false);

    panel.add(resultPanel, BorderLayout.SOUTH);

    inputField.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent evt) {

        calculate();

      }

    });

    celsiusButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent evt) {

        calculate();

      }

    });

    fahrenheitButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent evt) {

        calculate();

      }

    });

    pack();

    setVisible(true);

  }

  private void calculate() {

    String inputText = inputField.getText().trim();

    if (inputText.matches("\\d+(\\.\\d+)?")) {

      double value = Double.parseDouble(inputText);

      if (celsiusButton.isSelected()) {

        double result = value * 9 / 5 + 32;

        resultField.setText(String.format("%.2f 华氏度", result));

      } else {

        double result = (value - 32) * 5 / 9;

        resultField.setText(String.format("%.2f 摄氏度", result));

      }

    } else {

      resultField.setText("请输入有效的温度数值");

    }

  }

}

4. 数字转中文

本案例实现了一个将阿拉伯数字转换为中文数字的程序。比如说,输入123,程序会输出一百二十三。

代码实现:


public class NumberToChinese {

  public static void main(String[] args) {

    System.out.println(toChinese(123));

  }

  private static final String[] CHINESE_DIGITS = "六";

  private static final String[] CHINESE_UNITS = "十";

  public static String toChinese(int number) {

    if (number == 0) {//特判0

      return CHINESE_DIGITS[0];

    }

    String result = "";

    int unitIndex = 0;//当前处在数字的哪个位数(个位、十位、百位……)

    while (number > 0) {

      int digit = number % 10;//取出当前位上的数字

      if (digit != 0) {//如果当前位上的数字不是0

        result = CHINESE_DIGITS[digit] + CHINESE_UNITS[unitIndex] + result;//将当前位上的数字和当前位所代表的单位(十、百、千)添加到结果中

      } else {//如果当前位上的数字是0

        if (!result.startsWith(CHINESE_DIGITS[0])) {//特判连续的0

          result = CHINESE_DIGITS[0] + result;

        }

      }

      number /= 10;

      unitIndex++;

    }

    return result;

  }

}

5. 文件拷贝

本案例演示了如何用Java代码实现文件的拷贝。将文件A复制一份到文件B中。

代码实现:


import java.io.*;

public class FileCopy {

  public static void main(String[] args) throws Exception {

    copyFile("A.txt", "B.txt");

  }

  public static void copyFile(String sourceFilePath, String targetFilePath) throws Exception {

    FileInputStream fis = new FileInputStream(sourceFilePath);

    FileOutputStream fos = new FileOutputStream(targetFilePath);

    byte[] buffer = new byte[1024];

    int length;

    while ((length = fis.read(buffer)) > 0) {

      fos.write(buffer, 0, length);

    }

    fis.close();

    fos.close();

    System.out.println("文件拷贝成功!");

  }

}

、蒙特卡洛算法、阿拉伯数字、文件拷贝

  
  

评论区

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