java 基础知识学习2

目录

基础知识练习

String 类实现大小写转换的方法
public class Var { // 新建类
    public static void main(String[] args) { // 主方法
        String str = new String("hello WORD");
        // 转换为小写
        String newstr = str.toLowerCase();
        // 转换为大写
        String newstr2 = str.toUpperCase();
        System.out.println("转换为小写为:" + newstr);
        System.out.println("转换为大写为:" + newstr2);
    }
}
截取字符串中的部分内容
public class Eval { // 新建类
    public static void main(String[] args) { // 主方法
        String str = new String("We are students");
        String str2 = new String("I like Java");
        String newstr = str.substring(1, 3);
        String newstr2 = str2.substring(1, 3);
        if (newstr.equalsIgnoreCase(newstr2)) {
            System.out.println("两个字符相同");
        } else {
            System.out.println("两个字符不相同");
        }
    }
}
用正则表达式判断手机号码是否合法
public class Eval { // 新建类
    public static void main(String[] args) { // 主方法
        String regex = "^13\\d{9}|15[09]\\d{8}$";
        String text = "13000000000";
        if (text.matches(regex)) {
            System.out.println(text + " 是合法的手机号");
        }else{
            System.out.println(text + " 不是合法的手机号");
        }
    }
}
用字符串生成器追加字符
public class Eval { // 新建类
    public static void main(String[] args) { // 主方法
        String str = "CSDN";
        StringBuilder builder = new StringBuilder(str);
        for (int i = 1; i <= 10; i++) {
            builder.append(i);
        }
        System.out.println(builder.toString());
    }
}
用连接运算符”+”连接字符串
public class Example {
    public static void main(String[] args) {
        System.out.println("MWQ" + 9412);    // 与int型连接输出结果是MWQ9412
        System.out.println("10" + 7.5F);         // 与float型连接输出结果是107.5
        System.out.println("This is " + true);   // 与布尔型连接输出结果是This is true
        System.out.println("MR" + "MWQ");    // 字符串间连接输出结果是MRMWQ
        // 与引用类型连接输出结果是路径:C:\text.txt
        System.out.println("路径:" + (new java.io.File("C:/text.txt"))); 
        System.out.println();
        System.out.println(100 + 6.4 + "MR");    //字符串在后输出结果是106.4MR
        System.out.println("MR" + 100 + 6.4);    //字符串在前输出结果是MR1006.4
    }
}
去除字符串中的首尾控格
public class Example {
    public static void main(String[] args) {
        // 定义一个字符串,首尾均有空格
        String str = " ABC ";
        // 输出字符串的长度为5
        System.out.println(str + "长度为 : " + str.length());
        // 去掉字符串的首尾空格
        String str2 = str.trim();
        // 输出字符串的长度为3
        System.out.println(str2 + "长度为 : " + str2.length());
    }
}
获取字符串长度
public class Example {
    public static void main(String[] args) {
        String nameStr = "WuYang";
        int length = nameStr.length(); // 获得字符串的长度为10
        System.out.println(nameStr + " 的长度为:" + length);
    }
}
格式化时间
package com.ityang.java;
import java.util.Date;
public class Example {
    public static void main(String[] args) {
        Date today = new Date();
        // 格式化后为"03:06:53 下午"格式的时间
        String a = String.format("%tr", today); 
        // 格式化为"15:06:53"格式的时间
        String b = String.format("%tT", today); 
        // 格式化为"15:06"格式的时间
        String c = String.format("%tR", today); 
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}
格式化日期
package com.ityang.java;
import java.util.Date;
import java.util.Locale;

public class Example2 {
    public static void main(String[] args) {
        Date today = new Date();
        // 格式化后的字符串为月份的英文缩写
        String a = String.format(Locale.US, "%tb", today);  
        System.out.println("格式化后的字符串为月份的英文缩写: " + a);
        // 格式化后的字符串为月份的英文全写
        String b = String.format(Locale.US, "%tB", today);
        System.out.println("格式化后的字符串为月份的英文缩写: " + b);
        // 格式化后的字符串为星期(如:星期一)
        String c = String.format("%ta", today);
        System.out.println("月格式化后的字符串为星期: " + c);
        // 格式化后的字符串为星期(如:星期一)
        String d = String.format("%tA", today);
        System.out.println("格式化后的字符串为星期: " + d);
        // 格式化后的字符串为4位的年份值
        String e = String.format("%tY", today);
        System.out.println("格式化后的字符串为4位的年份值: " + e);
        // 格式化后的字符串为2位的年份值
        String f = String.format("%ty", today);
        System.out.println("格式化后的字符串为2位的年份值: " + f);
        // 格式化后的字符串为2位的月份值
        String g = String.format("%tm", today);
        System.out.println("格式化后的字符串为2位的月份值: " + g);
        // 格式化后的字符串为2位的日期值
        String h = String.format("%td", today);
        System.out.println("格式化后的字符串为2位的日期值: " + h);
        // 格式化后的字符串为1位的日期值
        String i = String.format("%te", today);
        System.out.println("格式化后的字符串为1位的日期值: " + i);
    }
}
字符串的切割
package com.ityang.java;
public class Example3 {
    public static void main(String[] args) {
        // 定义字符串
        String str = "book:and:food:and:drink";
        // 将字符串拆分为数组
        String[] arr = str.split(":",4);
        // 遍历数组元素
        for (String s : arr) {
            // 打印输出到控制台
            System.out.println("\"" + s + "\"");
        }
    }
}

进阶练习

用户登录验证
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = -401441768279319010L;
    private JPasswordField passwordField;
    private JTextField usernameText;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setTitle("用户登录");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/background.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        final JLabel usernameLable = new JLabel();
        usernameLable.setText("用户名:");
        usernameLable.setBounds(130, 166, 52, 18);
        backgroundPanel.add(usernameLable);

        final JLabel passwordLable = new JLabel();
        passwordLable.setText("密码:");
        passwordLable.setBounds(144, 199, 39, 18);
        backgroundPanel.add(passwordLable);

        usernameText = new JTextField();
        usernameText.setBounds(195, 164, 165, 22);
        backgroundPanel.add(usernameText);

        passwordField = new JPasswordField();
        passwordField.setBounds(195, 194, 165, 22);
        backgroundPanel.add(passwordField);

        final JButton submit = new JButton();
        submit.addActionListener(new ActionListener() {

            // 验证用户登录
            public void actionPerformed(final ActionEvent e) {
                // 从文本框中获取用户名
                String username = usernameText.getText();
                // 从密码框中获取密码
                String password = new String(passwordField.getPassword());
                // 用户登录信息
                String info = "";
                //判断用户名是否为null或空的字符串
                if(username == null || username.isEmpty()){
                    info = "用户名为空!";
                }
                //判断密码是否为null或空的字符串
                else if(password == null || password.isEmpty()){
                    info = "密码为空!";
                }
                //如果用户名与密码均为"mrsoft",则登录成功
                else if(username.equals("wuyang") && password.equals("wuyang")){
                    info = "恭喜,登录成功";
                }
                else{
                    info = "用户名或密码错误!";
                }
                // 通过对话框弹出用户登录信息
                JOptionPane.showMessageDialog(null,info);
            }
        });
        submit.setText("登录");
        submit.setBounds(162, 244, 69, 24);
        backgroundPanel.add(submit);

        final JButton reset = new JButton();
        reset.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 重置按钮方法
                // 清空用户名文本框
                usernameText.setText("");
                // 清空密码文本框
                passwordField.setText("");
            }
        });
        reset.setText("重置");
        reset.setBounds(276, 244, 69, 24);
        backgroundPanel.add(reset);
        //
    }

}
验证ip地址的有效性
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = -5588352205398329108L;
    private JTextArea textArea;
    private JTextField textField;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setTitle("验证IP地址的有效性");
        setResizable(false);
        setBounds(100, 100, 433, 227);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        textField = new JTextField();
        textField.setBounds(148, 45, 138, 19);
        backgroundPanel.add(textField);

        final JLabel label = new JLabel();
        label.setText("请输入IP地址:");
        label.setBounds(46, 45, 96, 17);
        backgroundPanel.add(label);

        textArea = new JTextArea();
        textArea.setBounds(46, 97, 331, 64);
        backgroundPanel.add(textArea);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                String text = textField.getText();
                // 实例化StringUtil类
                StringUtil val = new StringUtil();
                // 验证
                String info = val.matches(text);
                // 输出验证信息
                textArea.setText(info);
            }
        });
        button.setText("验证");
        button.setBounds(307, 43, 70, 22);
        backgroundPanel.add(button);

        final JLabel label_1 = new JLabel();
        label_1.setText("验证信息:");
        label_1.setBounds(46, 76, 82, 15);
        backgroundPanel.add(label_1);
        //
    }

}

----

/**
* IP地址验证类
* @author wuyang
*/
public class StringUtil {

/**
 * 验证ip是否合法
 * @param text ip地址
 * @return 验证信息
 */
public String matches(String text) {
    if(text != null && !text.isEmpty()){
        // 定义正则表达式
        String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +
                        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
                        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
                        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
        // 判断ip地址是否与正则表达式匹配
        if(text.matches(regex)){
            // 返回判断信息
            return text + "\n是一个合法的IP地址!";
        }else{
            // 返回判断信息
            return text + "\n不是一个合法的IP地址!";
        }
    }
    // 返回判断信息
    return "请输入要验证的IP地址!";
}

}


####鉴别非法电话号码


import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = -5588352205398329108L;
    private JTextArea textArea;
    private JTextField textField;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("鉴别非法电话号码");
        setBounds(100, 100, 456, 262);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        textField = new JTextField();
        textField.setBounds(155, 38, 155, 22);
        backgroundPanel.add(textField);

        textArea = new JTextArea();
        textArea.setBounds(51, 96, 336, 114);
        backgroundPanel.add(textArea);

        final JLabel label = new JLabel();
        label.setText("请输入电话号码:");
        label.setBounds(51, 40, 110, 18);
        backgroundPanel.add(label);

        final JLabel label_1 = new JLabel();
        label_1.setText("验证信息:");
        label_1.setBounds(51, 72, 66, 18);
        backgroundPanel.add(label_1);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 获取文本框中内容
                String text = textField.getText();
                // 设置返回结果
                textArea.setText(StringUtil.check(text));
            }
        });
        button.setText("验证");
        button.setBounds(327, 38, 60, 22);
        backgroundPanel.add(button);
        //
    }

}

public class StringUtil {
    public static String check(String text){
        if(text == null || text.isEmpty()){
            return "请输入电话号码!";
        }
        // 定义正则表达式
        String regex = "^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}$";
        // 判断输入数据是否为电话号码
        if(text.matches(regex)){
            return text + "\n是一个合法的电话号码!";
        }else{
            return text + "\n不是一个合法的电话号码!";
        }
    }
}
判断本地文件类型
/**
 * 自定义字符串工具类
 * @author wuyang 
 */
public class StringUtil {

    /**
     * 判断文件类型
     * @param name 文件名
     * @return 判断的结果信息
     */
    public static String getType(String name){
        // 提示信息
        String type = name + " : 未知文件类型!";
        // 判断扩展名
        if(name.endsWith(".jpg") || name.endsWith(".gif") || name.endsWith(".bmp")){
            type = name + " :\n 为图片文件!";
        }else if(name.endsWith(".java")){
            type = name + " :\n 为java文件!";
        }else if(name.endsWith(".txt")){
            type = name + " :\n 为文本文件!";
        }else if(name.endsWith(".pdf")){
            type = name + " :\n 为电子文档!";
        }else if(name.endsWith(".exe")){
            type = name + " :\n 为可执行文件!";
        }else if(name.endsWith(".doc")){
            type = name + " :\n 为word文档文件!";
        }else if(name.endsWith(".xls")){
            type = name + " :\n 为Excel电子表格!";
        }else if(name.endsWith(".rar")  || name.endsWith(".zip")){
            type = name + " :\n 为压缩文件!";
        }
        // 返回提示信息
        return type;
    }
}

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 1272119087959058558L;
    private JTextField textField;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("判断本地文件类型");
        setBounds(100, 100, 517, 146);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        textField = new JTextField();
        textField.setBounds(87, 47, 288, 22);
        backgroundPanel.add(textField);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 实例化文件选择类
                FileChooser fileChooser = new FileChooser();
                // 文件路径
                String filePath = fileChooser.getFilePath();
                // 文件名称
                String fileName = fileChooser.getFileName();
                // 将文件路径字符串放置到文本框中
                textField.setText(filePath);
                // 通过自定义字符串工具类判断文件类型
                String fileType = StringUtil.getType(fileName);
                // 消息提示文件类型
                JOptionPane.showMessageDialog(null, fileType);
            }
        });
        button.setText("打开文件");
        button.setBounds(392, 46, 90, 25);
        backgroundPanel.add(button);

        final JLabel label = new JLabel();
        label.setText("路径:");
        label.setBounds(32, 49, 49, 18);
        backgroundPanel.add(label);
        //
    }

}
命令行的简单实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    // 命令
    private static final String COMMAND = "java";
    // 主方法
    public static void main(String[] args) {
        BufferedReader br = null;
        while (true) {
            try {
                // 提示输入命令
                System.out.println("Please enter command:");
                // 获取输入
                br = new BufferedReader(new InputStreamReader(System.in));
                // 读取输入命令的字符串
                String in = br.readLine();
                // 执行命令
                command(in);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 执行命令
    public static void command(String s) {
        // 显示信息
        String message = "Usage: java [-Option]\n" + "where [options] are:\n"
                + "\t [-help,-?] \t显示帮助信息\n" + "\t [-ver] \t显示版本信息\n"
                + "\t [-home] \t显示吴杨博客主页地址\n" + "\t [-desc] \t显示程序的描述信息\n"
                + "\t [-exit] \t退出操作\n";
        // 判断所输入的命令是否是已指定的命令
        if (s.startsWith(COMMAND)) {
            // 判断所输入的命令的长度
            if (s.length() > COMMAND.length()) {
                // 判断命令的参数
                if (s.endsWith(" -help") || s.endsWith(" -?")) {
                    // 帮助信息
                } else if (s.endsWith(" -ver")) {
                    // 版本信息
                    message = "当前版本为2.0\n";
                } else if (s.endsWith(" -home")) {
                    // 主页信息
                    message = "吴杨的博客主页:http://blog.csdn.net/qq_28334041/article/details/66472712";
                } else if (s.endsWith(" -desc")) {
                    // 描述信息
                    message = "本程序意在搭建简单的命令行模式";
                } else if (s.endsWith(" -exit")) {
                    // 退出程序
                    System.out.println("您已退出命令行程序\n");
                    System.exit(0);
                } else {
                    // 未定义的参数值
                    message = "Error:不支持此命令!\n";
                }
            }
        } else if (s.equalsIgnoreCase("exit")) {
            // 退出程序
            System.out.println("您已退出命令行程序\n");
            System.exit(-1);
        } else {
            // 未定义的命令
            message = "'" + s + "' 不是内部或外部命令,也不是可运行程序\n" + "或批处理文件\n";
        }
        // 输出执行信息
        System.out.println(message);
    }
}

数组

冒泡排序
public class BubbleSort {
      public static void main(String[] args) {
            int[] array = new int[] { 5, 1, 2, 8, 4, 6, 9, 7, 3, 0 };
            int temp;                                                                  // 临时变量
            System.out.println("原有数组内容:");
            printArray(array);
            // 从小到大排序
            for (int i = 1; i < array.length; i++) {                                          // 排序数组的范围(整个数组)
                  for (int j = 0; j < array.length - i; j++) {                         // 比较相邻元素,较大的数往后冒泡
                        if (array[j] > array[j + 1]) {
                              temp = array[j];                                       // 交换相邻两个数
                              array[j] = array[j + 1];
                              array[j + 1] = temp;
                        }
                  }
            }
            System.out.println("从小到大排序后的结果:");
            printArray(array);                                                      // 输出冒泡排序后的数组内容
      }
      /**
       * 遍历数组的方法,该方法输出数组所有内容
       * @param array 要遍历的数组
       */
      public static void printArray(int[] array) {
            for (int i : array) {
                  System.out.print(i + " ");
            }
            System.out.println("\n");
      }
}
直接选择排序法
public class SelectSort {
      public static void main(String[] args) {
            int[] array = new int[] { 5, 1, 2, 8, 4, 6, 9, 7, 3, 0 };
            int temp;                                                           // 临时变量
            System.out.println("原有数组内容:");
            printArray(array);                                               // 输出原有数组
            int index;                                                           // 索引变量
            for (int i = 1; i < array.length; i++) {                                   // 正序排列
                  index = 0;
                  for (int j = 1; j <= array.length - i; j++) {
                        if (array[j] > array[index]) {
                              index = j;
                        }
                  }
                  // 交换在data.length-i和index两个位置上的数组元素
                  temp = array[array.length - i];
                  array[array.length - i] = array[index];
                  array[index] = temp;
            }
            System.out.println("正序排列数组内容:");
            printArray(array);                                               // 输出排序后的数组
      }
      /**
       * 遍历数组的方法,该方法输出数组所有内容
       * @param array 要遍历的数组
       */
      public static void printArray(int[] array) {
            for (int i : array) {
                  System.out.print(i + " ");
            }
            System.out.println("\n");
      }
}
快速排序法
public class QuickSort {
    public static void main(String[] args) {
        char[] array = { 'a', 'b', 'f', 'e', 'g', 'd', 'h', 'c', 'j', 'i' };
        System.out.println("原有数组内容:");
        printArray(array); // 输出原有数组
        quickSort(array, 0, array.length - 1);
        System.out.println("正序排列数组内容:");
        printArray(array); // 输出排序后的数组
    }

    /**
     * 快速排序方法
     * 
     * @param sortarray
     *            要排序的数组
     * @param lowIndex
     *            起始索引
     * @param highIndex
     *            最大索引
     */
    private static void quickSort(char sortarray[], int lowIndex, int highIndex) {
        int lo = lowIndex; // 记录最小索引
        int hi = highIndex; // 记录最大索引
        int mid; // 记录分界点元素
        if (highIndex > lowIndex) {
            mid = sortarray[(lowIndex + highIndex) / 2]; // 确定中间分界点元素值
            while (lo <= hi) {
                while ((lo < highIndex) && (sortarray[lo] < mid))
                    ++lo; // 确定不大于分界元素值的最小索引
                while ((hi > lowIndex) && (sortarray[hi] > mid))
                    --hi; // 确定大于分界元素值的最大索引
                if (lo <= hi) { // 如果最小与最大索引没有重叠
                    char temp = sortarray[lo]; // 交换数组元素
                    sortarray[lo] = sortarray[hi];
                    sortarray[hi] = temp; // 交换两个索引的元素
                    ++lo; // 递增最小索引
                    --hi; // 递减最大索引
                }
            }
            if (lowIndex < hi) // 递归排序没有未分解元素
                quickSort(sortarray, lowIndex, hi);
            if (lo < highIndex) // 递归排序没有未分解元素
                quickSort(sortarray, lo, highIndex);
        }
    }

    /**
     * 遍历数组的方法,该方法输出数组所有内容
     * 
     * @param array
     *            要遍历的数组
     */
    public static void printArray(char[] array) {
        for (char i : array) { // 遍历数组
            System.out.print(i + " "); // 输出数组内容
        }
        System.out.println("\n"); // 输出换行符
    }
}
反转数组中元素的顺序
public class ReverseSort {
    public static void main(String[] args) {
        // 创建一个数组
        int[] array = { 10, 20, 30, 40, 50, 60 };
        // 调用排序对象的方法将数组反转
        System.out.println("数组原有内容:");
        showArray(array);// 输出排序前的数组值
        int temp;
        int len = array.length;
        for (int i = 0; i < len / 2; i++) {
            temp = array[i];
            array[i] = array[len - 1 - i];
            array[len - 1 - i] = temp;
        }
        System.out.println("数组反转后内容:");
        showArray(array);// 输出排序后的数组值
    }

    /**
     * 显示数组所有元素
     * 
     * @param array
     *            要显示的数组
     */
    public static void showArray(int[] array) {
        for (int i : array) {// foreach格式遍历数组
            System.out.print("\t" + i);// 输出每个数组元素值
        }
        System.out.println();
    }
}
利用数组随机抽取幸运观众
public class ArrayExample {
    public static void main(String[] args) {
        // 定义人员数组
        String[] personnelArray = { "赵云", "张飞", "吕布", "貂蝉", "关羽", "诸葛亮", "刘备" };
        double randomNum = (double) Math.random(); // 生成随机数字
        int index = (int) (randomNum * personnelArray.length); // 把随机数转换为数组索引
        // 定义中奖信息
        String info = "本次抽取观众人员:\n\t" + personnelArray[index] + "\n恭喜"
                + personnelArray[index] + "成为本次观众抽奖的大奖得主。" + "\n\n我们将为"
                + personnelArray[index] + "颁发:\n\t过期的酸奶二十箱。";
        System.out.println(info);// 输出中奖信息}
    }
}

案列集锦

歌手打分小程序
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 6061185921095535754L;

    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("歌手打分程序");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        final DoubleText grade1 = new DoubleText();
        grade1.setBounds(303, 40, 125, 22);
        backgroundPanel.add(grade1);

        final JLabel label = new JLabel();
        label.setForeground(Color.WHITE);
        label.setText("评委一:");
        label.setBounds(238, 42, 59, 18);
        backgroundPanel.add(label);

        final JLabel label_1 = new JLabel();
        label_1.setForeground(Color.WHITE);
        label_1.setText("评委二:");
        label_1.setBounds(238, 79, 59, 18);
        backgroundPanel.add(label_1);

        final JLabel label_2 = new JLabel();
        label_2.setForeground(Color.WHITE);
        label_2.setText("评委三:");
        label_2.setBounds(238, 116, 59, 18);
        backgroundPanel.add(label_2);

        final JLabel label_3 = new JLabel();
        label_3.setForeground(Color.WHITE);
        label_3.setText("评委四:");
        label_3.setBounds(238, 157, 59, 18);
        backgroundPanel.add(label_3);

        final JLabel label_4 = new JLabel();
        label_4.setForeground(Color.WHITE);
        label_4.setText("评委五:");
        label_4.setBounds(238, 200, 59, 18);
        backgroundPanel.add(label_4);

        final DoubleText grade2 = new DoubleText();
        grade2.setBounds(303, 77, 125, 22);
        backgroundPanel.add(grade2);

        final DoubleText grade3 = new DoubleText();
        grade3.setBounds(303, 114, 125, 22);
        backgroundPanel.add(grade3);

        final DoubleText grade4 = new DoubleText();
        grade4.setBounds(303, 155, 125, 22);
        backgroundPanel.add(grade4);

        final DoubleText grade5 = new DoubleText();
        grade5.setBounds(303, 198, 125, 22);
        backgroundPanel.add(grade5);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 创建成绩数组
                double[] grades = {
                        grade1.getDouble(),grade2.getDouble(),grade3.getDouble(),grade4.getDouble(),grade5.getDouble()
                    };
                // 对数组排序
                Arrays.sort(grades);
                // 总分
                double sum = 0;
                // 最低分
                double min = grades[0];
                // 最高分
                double max = grades[grades.length - 1];
                // 计算去掉最高分与最低分的分数总和
                for (int i = 1; i < grades.length - 1 ; i++) {
                    sum += grades[i];
                }
                // 实例化DecimalFormat对象,用于格式化十进制数字
                DecimalFormat format = new DecimalFormat();
                // 设置格式化格式
                format.applyPattern("#.##");
                // 计算平均分
                double avg = sum/3;
                // 实例化StringBuffer对象
                StringBuffer sb = new StringBuffer();
                // 追加最低分
                sb.append("去掉一个最低分:" + format.format(min) + " 分\n");
                // 追加最高分
                sb.append("去掉一个最高分:" + format.format(max) + " 分\n");
                // 追加平均分
                sb.append("平均得分:" + format.format(avg) + " 分");
                // 弹出提示窗口
                JOptionPane.showMessageDialog(null, sb.toString());
            }
        });
        button.setIcon(SwingResourceManager.getIcon(MainFrame.class, "/res/bt.png"));
        button.setBounds(284, 249, 103, 31);
        backgroundPanel.add(button);
        //
    }

}

数组的基础练习

创建数组和数组之间数据的复制
import java.util.Arrays; //导入java.util.Arrays类
public class Eval {      // 创建类
    public static void main(String[] args) {
        // 创建数组arr1
        int arr1[] = new int[] { 1, 2, 3, 4, 5 };
        // 创建数组arr2
        int arr2[] = Arrays.copyOf(arr1, 3);
        // 复制源数组中从下标0开始的3个元素到目的数组,从下标0的位置开始存储。
        System.out.println("数组arr1:");
        // 遍历数组并输出元素
        for (int i = 0; i < arr1.length; i++){
            System.out.print(arr1[i]);
        }
        System.out.println();
        System.out.println("数组arr2:");
        // 遍历数组并输出元素
        for (int j = 0; j < arr2.length; j++){
            System.out.print(arr2[j]);
        }
    }
}
对数组排序并输出数组中最小的值
import java.util.Arrays;
public class Eval { // 创建类
    public static void main(String[] args) {
        int arr[] = new int[] { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
        //对数组按升序进行排序
        Arrays.sort(arr);
        System.out.println("排序后的数组为:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println();
        //输出数组中的最小值
        System.out.println("最小值为: " + arr[0]);
    }
}
将数组中指定索引位置的元素替换
import java.util.Arrays;
public class Eval { // 创建类
    public static void main(String[] args) {
        // 创建字符串数组
        String arr[] = new String[] { "ac", "bc", "dc", "yc" };
        // 打印数组
        print(arr);
        // 将数组的第3个元素填充为"bb"
        Arrays.fill(arr, 2, 3, "bb");
        // 打印数组
        print(arr);
    }
    // 打印数组中的元素
    public static void print(String[] arr){
        // 遍历数组
        for (String str : arr) {
            System.out.print(str + " ");
        }
        System.out.println();
    }
}
将二维数组的行列互换
public class Eval { // 创建类
    public static void main(String[] args) {
        // 创建2维数组
        int arr[][]= new int[][]{
                {1,2,3},
                {4,5,6},
                {7,8,9}};
        System.out.println("行列互调前:");
        // 输出2维数组
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("行列互调后:");
        // 输出2维数组
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[j][i] + " ");
            }
            System.out.println();
        }
    }
}
实现数组的复制功能
import java.util.Arrays;
public class Example {
    public static void main(String[] args) {
        // 创建数组arr1
        int arr1[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
        // 通过复制arr1创建数组arr2
        int arr2[] = Arrays.copyOf(arr1, arr1.length);
        // 遍历数组并打印输出
        for (int i = 0; i < arr2.length; i++) {
            System.out.print(arr2[i] + " ");
        }
    }
}
排序数组并输出排序后的数组
import java.util.Arrays;
public class Example {
    public static void main(String[] args) {
        // 创建int型数组num
        int[] num = { 30, 20, 25, 40, 8 };
        System.out.println("排序前:");
        print(num);
        // 对数组进行排序
        Arrays.sort(num);
        System.out.println("排序后:");
        print(num);
    }
    public static void print(int[] arr){
        // 遍历数组并打印输出
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}
获得一维数组的长度 并输出
public class Example {
    public static void main(String[] args) {
        // 创建int型数组
        int[] arrInt = new int[12];
        // 创建boolean型数组
        boolean arrBoolean[] = new boolean[4];
        // 输出数组的长度
        System.out.println("arrInt 的长度为:" + arrInt.length); // 输出值为12
        System.out.println("arrBoolean 的长度为:" + arrBoolean.length); // 输出值为4
    }
}
利用一维数组输出7行杨辉三角形
public class Example {
    public static void main(String[] args) {
        int i, yh[] = new int[7];
        for (i = 0; i < 7; i++) {
            yh[i] = 1;
            for (int j = i - 1; j > 0; j--)
                yh[j] = yh[j - 1] + yh[j];
            for (int j = 0; j <= i; j++)
                System.out.print(yh[j] + "\t");
            System.out.println();
        }
    }
}
利用for循环输出二维数组中的值
public class Example {
    public static void main(String[] args) {
        // 创建二维数组
        int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
        // 遍历二维数组并输出其中的元素
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++){
                System.out.print(arr[i][j]+"  ");
            }
            System.out.println();
        }
    }
}
用for循环为int 型数组赋值
public class Example {
    public static void main(String[] args) {
        // 声明数组时,方括号可以写在数据类型的右侧,也可以写在数组名的右侧
        int[] num = new int[10]; // num是数组名,方括号在数据类型右侧
        // 对数组元素赋值
        for (int i = 0; i < 10; i++) {
            num[i] = i + 1;
        }
        // 遍历数组并输出
        for (int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
    }
}
将字符串反向输出
/**
 * 数组工具类
 * @author wuyang
 */
public class ArrayUtil {
    // 反转字符串方法
    public static String reverse(String text){
        // 实例化StringBuffer
        StringBuffer sb = new StringBuffer();
        // 判断字符串是否为空
        if(text != null && !text.isEmpty()){
            // 将字符串转为字符数组
            char[] arr = text.toCharArray();
            // 反向获取
            for(int i = arr.length - 1; i >=0; i--){
                sb.append(arr[i]);
            }
        }
        // 返回转字符串
        return sb.toString();
    }
}

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import com.lzw.BackgroundPanel;
import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = -1368705126832671635L;
    private JTextField textField_1;
    private JTextField textField;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("字符串反向输出");
        setBounds(100, 100, 484, 242);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        textField = new JTextField();
        textField.setBounds(97, 65, 278, 22);
        backgroundPanel.add(textField);

        final JLabel label = new JLabel();
        label.setText("请输入:");
        label.setBounds(97, 41, 52, 18);
        backgroundPanel.add(label);

        textField_1 = new JTextField();
        textField_1.setBounds(97, 143, 278, 22);
        backgroundPanel.add(textField_1);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 获取所输入的字符串
                String text = textField.getText();
                // 判断输入内容是否有效
                if(text == null || text.isEmpty()){
                    // 提示错误信息
                    JOptionPane.showMessageDialog(null, "请输入内容!");
                }else{
                    // 将字符串反转
                    textField_1.setText(ArrayUtil.reverse(text));
                }
            }
        });
        button.setText("反转");
        button.setBounds(186, 104, 69, 22);
        backgroundPanel.add(button);
        //
    }

}
简易电子时钟
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.Calendar;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 7791539566768257092L;

    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setTitle("简易电子时钟");
        setResizable(false);
        setBounds(100, 100, 362, 152);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final ClockPanel clockPanel = new ClockPanel();
        getContentPane().add(clockPanel, BorderLayout.CENTER);

        final JLabel label = new JLabel();
        label.setForeground(Color.ORANGE);
        label.setFont(new Font("黑体", Font.BOLD, 22));
        // 定义数组
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; 
        // 实例化Calendar对象
        Calendar c = Calendar.getInstance();
        // 获取今天是一周的第几天
        int index = c.get(Calendar.DAY_OF_WEEK) - 1;
        // 输出结果
        label.setText(weeks[index]);
        label.setBounds(136, 72, 92, 25);
        clockPanel.add(label);
    }

}
随机获取试题
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextPane;

import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 6061185921095535754L;

    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setTitle("随机抽奖");
        setBounds(100, 100, 429, 286);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/res/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        final JLabel label = new JLabel();
        label.setForeground(Color.BLUE);
        label.setFont(new Font("", Font.BOLD, 14));
        label.setBounds(76, 52, 203, 28);
        backgroundPanel.add(label);

        final JTextPane textPane = new JTextPane();
        textPane.setForeground(new Color(255, 255, 255));
        textPane.setFont(new Font("", Font.BOLD, 14));
        textPane.setOpaque(false);
        textPane.setBounds(88, 100, 271, 121);
        backgroundPanel.add(textPane);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                //创建试题数组
                String[][] questions = {
                        {"脑筋急转弯","1+1在什么情况不等于2?"},
                        {"抢答题","1+1在什么情况等于2?"},
                        {"脑筋急转弯","地上一个猴,树上骑个\n猴,总共有几只猴?"},
                        {"抢答题","明天的明天的明天是哪一天?"},
                        {"计算题","55*55等于多少?"}
                };
                // 实例化Random用于生成随机数
                Random rand = new Random();
                // 生成随机数
                int index = rand.nextInt(questions.length);
                // 获取试题
                String[] ques = questions[index];
                // 显示题目 
                label.setText(ques[0]);
                // 显示内容
                textPane.setText(ques[1]);
            }
        });
        button.setText("抽取试题");
        button.setBounds(325, 10, 86, 28);
        backgroundPanel.add(button);
    }

}
学生信息管理
/**
 * 自定义数组工具类
 * @author wuyang
 */
public class ArrayUtil {
    // 创建学生信息集合数组
    private static String[][] students;
    /**
     * 向学生集合数组中添加学生信息
     * @param student 学生信息
     * @return 学生集合数组
     */
    public static String[][] add(String[] student){
        // 判断学生信息数据是否有效
        if(student == null || student.length != 4){
            return null;
        }
        // 判断学生信息数据是否已创建
        if(students == null){
            // 实例化学生信息数据
            students = new String[][]{
                    {student[0],student[1],student[2],student[3]}
            };
        }else{
            // 创建一个二维数组
            String[][] temp = new String[students.length + 1][student.length];
            // 将学生信息数据复制到二维数组中
            System.arraycopy(students, 0, temp, 0, students.length);
            // 将新的学生数据添加到二维数组temp中
            for (int i = 0; i < student.length; i++) {
                // 添加数据
                temp[temp.length -1][i] = student[i];
            }
            // 更新数组
            students = temp;
        }
        // 返回所有学生信息
        return students;
    }
}

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import com.lyq.StudentPanel;

public class MainFrame extends JFrame {

    private static final long serialVersionUID = 746654481079475727L;
    private JTextField tf_sex;
    private JTextField tf_age;
    private JTextField tf_name;
    private JTextField tf_id;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("学生信息管理");
        getContentPane().setLayout(null);
        setBounds(100, 100, 402, 288);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JLabel label = new JLabel();
        label.setHorizontalAlignment(SwingConstants.RIGHT);
        label.setText("学号:");
        label.setBounds(10, 25, 66, 18);
        getContentPane().add(label);

        final JLabel label_1 = new JLabel();
        label_1.setHorizontalAlignment(SwingConstants.RIGHT);
        label_1.setText("年龄:");
        label_1.setBounds(10, 64, 66, 18);
        getContentPane().add(label_1);

        final JLabel label_2 = new JLabel();
        label_2.setHorizontalAlignment(SwingConstants.RIGHT);
        label_2.setText("姓名:");
        label_2.setBounds(170, 25, 66, 18);
        getContentPane().add(label_2);

        final JLabel label_3 = new JLabel();
        label_3.setHorizontalAlignment(SwingConstants.RIGHT);
        label_3.setText("性别:");
        label_3.setBounds(170, 64, 66, 18);
        getContentPane().add(label_3);

        tf_id = new JTextField();
        tf_id.setBounds(82, 23, 87, 22);
        getContentPane().add(tf_id);

        tf_name = new JTextField();
        tf_name.setBounds(242, 23, 87, 22);
        getContentPane().add(tf_name);

        tf_age = new JTextField();
        tf_age.setBounds(82, 62, 87, 22);
        getContentPane().add(tf_age);

        tf_sex = new JTextField();
        tf_sex.setBounds(242, 62, 87, 22);
        getContentPane().add(tf_sex);

        final StudentPanel studentPanel = new StudentPanel();

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 获取学号
                String id = tf_id.getText();
                // 获取姓名
                String name = tf_name.getText();
                // 获取年龄
                String age = tf_age.getText();
                // 获取性别
                String sex = tf_sex.getText();
                // 获取学号
                if(!id.isEmpty() && !name.isEmpty() && !age.isEmpty() && !sex.isEmpty()){
                    // 使用数组创建一条学生信息数据
                    String[] student = {id,name,age,sex};
                    // 将学生信息添加到集合中
                    String[][] students = ArrayUtil.add(student);
                    // 显示学生信息
                    studentPanel.setStudents(students);
                }
            }
        });
        button.setText("添加");
        button.setBounds(250, 96, 79, 22);
        getContentPane().add(button);


        studentPanel.setBounds(0, 145, 395, 117);
        getContentPane().add(studentPanel);
        //
    }

}
金额大小写转换
import java.text.DecimalFormat;

import javax.swing.JOptionPane;

/**
 * 金额转换
 * @author wuyang
 */
public class ConvertMoney {
    // 大写数字
    private final static String[] STR_NUMBER = { "零", "壹", "贰", "叁", "肆", "伍",
            "陆", "柒", "捌", "玖" };
    // 单位
    private final static String[] STR_UNIT = { "", "拾", "佰", "仟", "万", "拾",
            "佰", "仟", "亿", "拾", "佰", "仟" };
    // 单位
    private final static String[] STR_UNIT2 = {"厘","分","角"};

    /**
     * 获取可数部分
     * @param num 金额
     * @return 金额整数部分
     */
    public static String getInteger(String num) {
        // 判断是否包含小数点
        if (num.indexOf(".") != -1) {
            num = num.substring(0, num.indexOf("."));   
        }
        // 反转字符串
        num = new StringBuffer(num).reverse().toString();
        // 创建一个StringBuffer对象
        StringBuffer temp = new StringBuffer();
        // 加入单位
        for (int i = 0; i < num.length(); i++) {
            temp.append(STR_UNIT[i]);
            temp.append(STR_NUMBER[num.charAt(i) - 48]);
        }
        // 反转字符串
        num = temp.reverse().toString();
        num = numReplace(num, "零拾", "零");   // 替换字符串的字符
        num = numReplace(num, "零佰", "零");   // 替换字符串的字符
        num = numReplace(num, "零仟", "零");   // 替换字符串的字符
        num = numReplace(num, "零万", "万");   // 替换字符串的字符
        num = numReplace(num, "零亿", "亿");   // 替换字符串的字符
        num = numReplace(num, "零零", "零");   // 替换字符串的字符
        num = numReplace(num, "亿万", "亿");   // 替换字符串的字符
        // 如果字符串以零结尾将其除去
        if(num.lastIndexOf("零") == num.length()-1){
            num = num.substring(0, num.length() -1);
        }
        return num;
    }
    /**
     * 获取小数部分
     * @param num 金额
     * @return 金额的小数部分
     */
    public static String getDecimal(String num){
        // 判断是否包含小数点
        if (num.indexOf(".") == -1) {
            return "";
        }
        num = num.substring(num.indexOf(".") + 1);
        //反转字符串
        num = new StringBuffer(num).reverse().toString();
        // 创建一个StringBuffer对象
        StringBuffer temp = new StringBuffer();
        // 加入单位
        for (int i = 0; i < num.length(); i++) {
            temp.append(STR_UNIT2[i]);
            temp.append(STR_NUMBER[num.charAt(i) - 48]);
        }
        // 替换字符串的字符
        num = temp.reverse().toString();
        num = numReplace(num, "零角", "零");   // 替换字符串的字符
        num = numReplace(num, "零分", "零");   // 替换字符串的字符
        num = numReplace(num, "零厘", "零");   // 替换字符串的字符
        num = numReplace(num, "零零", "零");   // 替换字符串的字符
        // 如果字符串以零结尾将其除去
        if(num.lastIndexOf("零") == num.length()-1){
            num = num.substring(0, num.length() -1);
        }
        return num;
    }
    /**
     * 替换字符串中内容
     * @param num 字符串
     * @param oldStr 被替换内容
     * @param newStr 新内容
     * @return 替换后的字符串
     */
    public static String numReplace(String num,String oldStr,String newStr){
        while(true){
            // 判断字符串中是否包含指定字符
            if(num.indexOf(oldStr) == -1){
                break;
            }
            // 替换字符串 
            num = num.replaceAll(oldStr, newStr);
        }
        // 返回替换后的字符串
        return num;
    }

    /**
     * 金额转换
     * @param d 金额
     * @return 转换成大写的全额
     */
    public static String convert(double d){
        // 实例化DecimalFormat对象
        DecimalFormat df = new DecimalFormat("#0.###");
        // 格式化double数字
        String strNum = df.format(d);
        // 判断是否包含小数点
        if (strNum.indexOf(".") != -1) {
            String num = strNum.substring(0, strNum.indexOf("."));
            // 整数部分大于12不能转换
            if(num.length() > 12){
                JOptionPane.showMessageDialog(null, "数字太大,不能完成转换!");
                return "";
            }
        }
        // 小数点
        String point = "";
        if(strNum.indexOf(".") != -1){
            point = "元";
        }else{
            point = "元整";
        }
        // 转换结果
        String result = getInteger(strNum) + point + getDecimal(strNum);
        // 判断是字符串是否已"元"结尾
        if(result.startsWith("元")){
            // 截取字符串
            result = result.substring(1, result.length());
        }
        // 返回新的字符串
        return result;
    }
}

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextPane;

import com.swtdesigner.SwingResourceManager;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 1272119087959058558L;
    private DoubleText doubleText;
    /**
     * Launch the application
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("金额大小写转换程序");
        setBounds(100, 100, 450, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final BackgroundPanel backgroundPanel = new BackgroundPanel();
        backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/bg.jpg"));
        getContentPane().add(backgroundPanel, BorderLayout.CENTER);

        final JLabel label = new JLabel();
        label.setText("小写金额:");
        label.setBounds(29, 160, 66, 18);
        backgroundPanel.add(label);

        doubleText = new DoubleText();
        doubleText.setBounds(107, 158, 218, 22);
        backgroundPanel.add(doubleText);

        final JTextPane textPane = new JTextPane();
        textPane.setBounds(29, 192, 387, 52);
        backgroundPanel.add(textPane);

        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                // 获取金额
                double value = doubleText.getDouble();
                // 将金额转换大写
                String valueCase = ConvertMoney.convert(value);
                // 将转换后的金额显示在textPane中
                textPane.setText(valueCase);
            }
        });
        button.setText(">>");
        button.setBounds(339, 155, 77, 23);
        backgroundPanel.add(button);



        //
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值