Java程序设计课程,使用eclipse集成开发环境 和 editpuls编辑器(java配置)
第一讲 Java语言与面向对象设计
1、Java语言,从C++发展而来,是C++的简化版,简单易学,纯面向对象,与平台无关,支持多线程,安全稳定
Java拥有丰富的类库,可以面向对象的应用开发、各类网络应用程序的开发,Internet的系统管理,数据库操作等等
2、类是具有共同属性和行为的对象的集合,类是对象的抽象,对象是类的实例
第二讲 简单的Java程序
Java文件名要与public类的类名一致,一个文件只能有一个public类
applet程序(界面库 javaFx,swing(JFrame,JApplet,JPanel),awt( 图形库graphics ))
package week1.applet;
import java.awt.Graphics;
import javax.swing.JApplet;
public class SayHelloApplet extends JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void paint(Graphics g){
g.drawString("Hello World", 20, 20);
}
}
命令行下设定path和classpath:set path是命令(javac及Java)的路径,set classpath是所要引用的类库的路径
第三讲 数据运算、流控制和数组
Java7以上,整形常量可以用二进制数表示,以0b或0B开头
Java浮点型常量默认为double类型,要声明常量为float,需要在数字后面加f或F
Java中没有无符号数,可以用long来处理无符号整数
课程代码
1、计算字符串中无重复字符的子串长度
![](https://i-blog.csdnimg.cn/blog_migrate/55f173513fe35f946a93285975503024.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/43cb7d0c90e8021d615b04dfec154e90.gif)
package lengthOfLongestSubstring;
import java.util.Scanner;
public class Main
{
int lengthOfLongestSubstring(String s)
{
int size = s.length();/*字符串长度*/
int[] dict = new int[256];
for(int i=0; i<256; ++i)
dict[i] = -1;
int maxlen = 0;/*最大无重复字符子串长度*/
int start = -1;/*无重复字符子串开始的位置*/
for (int i = 0; i<size; ++i)
{
if (dict[s.charAt(i)] > start) /*一旦字符有了位置记录 说明字符出现重复*/
{
start = dict[s.charAt(i)]; /*把该字符上次出现的位置 记录为字符串开始位置*/
}
dict[s.charAt(i)] = i; /*记录字符出现的位置 更新*/
maxlen = maxlen>i-start? maxlen: i-start;/*实时计算无重复字符串长度*/
}
return maxlen;/*返回最大无重复字符串长度*/
}
public static void main(String[] args)
{
Main m = new Main();
Scanner in = new Scanner(System.in);
String s = in.next();
System.out.println(m.lengthOfLongestSubstring(s));
in.close();
}
}
编程题代码,仅供参考
第二讲 简单的Java程序
![](https://i-blog.csdnimg.cn/blog_migrate/07d442b2baf3775c00d8a56379e0288c.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/801bf6e2fe1352defdc8af9887f792aa.gif)
package week2;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 3^3 + 4^3 + 5^3 = 6^3
int sum = 0;
final int first = 3;
final int last = 5;
final int result = 6;
for (int x = first; x <= last; ++x) {
sum += x * x * x;
}
if (sum == result * result * result)
System.out.print("yes!");
else
System.out.print("No!");
*/
/*
* 6^3 + ... + 69^3 = 180^3
int sum = 0;
final int first = 6;
final int last = 69;
final int result = 180;
for (int x = first; x <= last; ++x) {
sum += x * x * x;
}
if (sum == result * result * result)
System.out.print("yes!");
else
System.out.print("No!");
*/
//更多的情况
int sum = 0;
int first = 1;
final int last = 1000;
for (int i = 1; i < last / 2; ++i) {
first = i;
sum = 0;
for (int x = first; x <= last; ++x) {
sum += x * x * x;
for (int k = x + 1; k <= last; ++k) {
if (sum == k * k * k) {
System.out.printf("first=%d,...", first);
System.out.printf("last=%d,", x);
System.out.printf("result=%d\n", k);
}
}
}//end of for
}//end of for
}//end of main
}// end of class
![](https://i-blog.csdnimg.cn/blog_migrate/98fdb54008601b348a28e85fc8ce26d0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4b16e5b542ab2fb9ede0b0a950ed9f47.gif)
public class Test
{
public static void main(String[] args)
{
final int last = 1000;
for (int first = 1; first < last / 2; ++first) {
int sum = 0;
for (int x = first; x <= last; ++x) {
sum += x * x * x;
int k = x + 1;
for( ; k * k * k < sum && k <= last; ++k)
;
if (sum == k * k * k) {
System.out.printf("first=%d,...", first);
System.out.printf("last=%d,", x);
System.out.printf("result=%d\n", k);
}
}
}
}
}
第三讲 数据运算、流控制和数组
![](https://i-blog.csdnimg.cn/blog_migrate/2b7aa51031d07da597a26f9369dad897.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/7dfcc22f1442b1e65e7e1da9f445d30e.gif)
package week3;
public class Prime {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] prime = new int[100]; // 保存素数
boolean[] is_prime = new boolean[100]; // true表示i是素数
int p = 0;
for (int i = 0; i < 100; i++)// 初始化
{
is_prime[i] = true;
}
is_prime[0] = is_prime[1] = false; // 0,1不是素数
for (int i = 2; i < 100; i++) {
if (is_prime[i]) //
{
prime[p++] = i; // 计算素数的个数,也记录下了素数
for (int j = 2 * i; j < 100; j += i)// 除掉了i的倍数的数字
{
is_prime[j] = false;
}
}
}
for (int pr : prime) {
if (pr > 0)
System.out.print(pr + " ");
}
}
}
第四讲 类、包和接口
![](https://i-blog.csdnimg.cn/blog_migrate/84dcee0b3bb18870600aa55b62cdcd44.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/5b5628256c2745d85c5c7dba157e8477.gif)
package week4;
//接口
interface Flyable {
void fly();// 默认public abstract
}
// 抽象类
abstract class Anmial implements Flyable {
@Override // 覆盖
public void fly() {
System.out.println("开始飞行");
System.out.println("飞行结束");
}
}
public class Bird extends Anmial {
private String bird;
// static final字段
protected static final int distance = 100;
// setter
public void setter(String bird) {
this.bird = bird;
}
// getter
public String getter() {
return bird;
}
// 飞翔
@Override // 覆盖
public void fly() {
System.out.println(this.bird + "开始飞行");
System.out.println("开始" + distance + "米飞行中");
System.out.println(getter() + "飞行结束\n");// 使用getter
}
// main函数
public static void main(String[] args) {
System.out.println("飞翔接力正式开始!\n");
String bir1 = "bird1";
String bir2 = "bird2";
Bird bird1 = new Bird();
bird1.setter(bir1);
bird1.fly();
Bird bird2 = new Bird();
bird2.setter(bir2);
bird2.fly();
System.out.println("飞翔接力结束!\n");
}
}
第五讲 深入理解Java语言
![](https://i-blog.csdnimg.cn/blog_migrate/de1b91e7969d218fe64c607310e2bbc7.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/8d66493872d689d8f631a4a9f80ea68c.gif)
package week5;
/**
* 一个简单的新闻事件侦听演示程序
* @author tds
* @author 修改者:金色的省略号
*/
public class NewsDemo {
public static void main(String[] args) {
//模拟有一家新闻社
NewsAgency bbc = new NewsAgency("BBC");
//订阅该社的新闻
bbc.addListener(new MyListener());
//TODO 请在这里再加入一个Listener
//1.匿名类
bbc.addListener(new Listener(){
//当接收到消息后,进行一些显示
public void newsArrived(NewsEvent e){
if( e.level>5) System.out.println("warning :");
System.out.println("please note," + e.text + " happed!");
}
});
//2.lambda表达式
bbc.addListener((NewsEvent e)->
{
if( e.level>5) System.out.println("warning :");
System.out.println("please note," + e.text + " happed!");
}
);
//新闻社启动其工作流程
bbc.start();
}
}
/**
* 事件信息
*/
class NewsEvent{
Object source; //事件来源
String text; //事件内容
int level; //事件级别
NewsEvent(Object source, String text, int level){
this.source=source;
this.text = text;
this.level = level;
}
}
interface Listener{
void newsArrived(NewsEvent e);
}
/**
* 新闻机构
*/
class NewsAgency {
String name; //机构名
public NewsAgency(String name) {
this.name = name;
}
Listener[] listeners = new Listener[100]; //侦听者(订阅者)
int listenerCnt = 0; //已有的订阅者
//加入一个订阅者
void addListener(Listener oneListener){
if(listenerCnt<listeners.length){
listeners[listenerCnt] = oneListener;
listenerCnt++;
}
}
//模拟一个事件发生,并通知所有的订阅者
void start(){
NewsEvent event = new NewsEvent("Mr. Joan", "Bombing", 9 );
for(int i=0; i<listenerCnt; i++) {
listeners[i].newsArrived(event);
}
}
}
/**
* 实现一个订阅者
*/
class MyListener implements Listener{
//当接收到消息后,进行一些显示
public void newsArrived(NewsEvent e){
if( e.level>5) System.out.println("warning :");
System.out.println("please note," + e.text + " happed!");
}
}
第六讲 异常处理
package week6;
//自定义一个异常类,继承自系统的异常类Exception
class MyException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
// 构造方法
public MyException(String msg) {
super(msg);
}
}
// 使用自定义的异常
public class TestMyException {
// 在一个函数中抛出异常
public static void MyExc() throws MyException {
throw new MyException("MyExc() method occurs an exception! ");
}
// 调用这个函数并捕获异常。
public static void main(String[] args) {
try {
TestMyException.MyExc();
} catch (MyException e1) {
System.out.println("MyException: " + e1.getMessage());
// e1.printStackTrace();//显示调用堆栈的跟踪信息
}
}
}
第七讲 工具类及常用算法
![](https://i-blog.csdnimg.cn/blog_migrate/a2ed16c142afab697e0339723c7a142a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/1df109e0c86bd4cd089a692d82c4dd10.gif)
package week7;
import java.util.ArrayList;
import java.util.Scanner;
//账户类
class account {
private String username;
private String password;
private double balance;
// 构造
public account(String _username, String _password, double _balance) {
username = _username;
password = _password;
balance = _balance;
}
// 取款
void withdraw(double _balance) {
if (balance >= _balance) {
balance -= _balance;
System.out.println("当前余额是:" + balance);
} else {
System.out.println("余额不足");
}
}
// 存款
void deposit(double _balance) {
balance += _balance;
System.out.println("当前余额是:" + balance);
}
String getUsername() {
return username;
}
String getUpassword() {
return password;
}
double getBalance() {
return balance;
}
}
class Mybank {
private String bankName;
// 账户列表
private ArrayList<account> arr;
// 构造
Mybank(String _bankName) {
setBankName(_bankName);
arr = new ArrayList<>();
}
// 开户
void openAccount() {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("请输入用户名、密码、开户金额:");
account a = new account(in.next(), in.next(), in.nextDouble());
arr.add(a);
System.out.println("继续,请输入y,退出输入n");
String s = in.next();
if (s.equals("n"))
break;
}
//in.close(); //为何不能关闭?
}
// 取款
void drawAccount() {
while (true) {
Scanner in = new Scanner(System.in);
System.out.println("请输入用户名、密码及取款数额:");
String _username = in.next();
String _password = in.next();
double _balance = in.nextDouble();
boolean b = true;
for (account a : arr) {
if (a.getUsername().equals(_username) && a.getUpassword().equals(_password)) {
a.withdraw(_balance);
b = false;
break;
}
}
if (b)
System.out.println("用户名或密码错误!");
System.out.println("继续取款,请输入y,退出输入n");
String s = in.next();
if (s.equals("n"))
break;
in.close();
}
}
// 存款
void depositAccount() {
while (true) {
Scanner in = new Scanner(System.in);
System.out.println("请输入用户名、密码及存款数额:");
String _username = in.next();
String _password = in.next();
double _balance = in.nextDouble();
boolean b = true;
for (account a : arr) {
if (a.getUsername().equals(_username) && a.getUpassword().equals(_password)) {
a.deposit(_balance);
b = false;
break;
}
}
if (b)
System.out.println("用户名或密码错误!");
System.out.println("继续存款,请输入y,退出输入n");
String s = in.next();
if (s.equals("n"))
break;
in.close();
}
}
// 查询
void checkAccount() {
while (true) {
Scanner in = new Scanner(System.in);
System.out.println("请输入用户名、密码:");
String _username = in.next();
String _password = in.next();
boolean b = true;
for (account a : arr) {
if (a.getUsername().equals(_username) && a.getUpassword().equals(_password)) {
System.out.println("你的账户余额:" + a.getBalance());
b = false;
break;
}
}
if (b)
System.out.println("用户名或密码错误!");
System.out.println("继续查找,请输入y,退出输入n");
String s = in.next();
if (s.equals("n"))
break;
in.close();
}
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
}
// 测试类
public class test {
public static void main(String[] args) {
Mybank m = new Mybank("我的银行");
Scanner in = new Scanner(System.in);
// 测试面板
label: while (true) {
System.out.println("开户请按1,存款请按2,取款请按3," + "查询请按4,退出请按5");
String s = in.next();
switch (s) {
case "1":
m.openAccount();
break;
case "2":
m.depositAccount();
break;
case "3":
m.drawAccount();
break;
case "4":
m.checkAccount();
break;
case "5":
break label;
}
}
in.close();
}
}
第八讲 多线程
![](https://i-blog.csdnimg.cn/blog_migrate/91c2c8c83b1f41a0e202eeff672b97d5.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/7ce260107dda4242032eb6314f85ba81.gif)
package week8;
import java.net.URL;
import java.io.*;
import java.util.Date;
class ThreadDownload
{
public static void main(String[] args)
throws IOException
{
final URL[] urls = {
new URL("https://www.pku.edu.cn"),
new URL("https://www.baidu.com"),
new URL("https://www.sina.com.cn"),
new URL("https://www.dstang.com")
};
final String[] files = {
"pku.htm",
"baidu.htm",
"sina.htm",
"study.htm",
};
for(int i=0; i<urls.length; i++){
final int idx = i;
new Thread( ()-> {
try{
System.out.println( urls[idx]);
download( urls[idx], files[idx]);
}catch(Exception ex){
ex.printStackTrace();
}
}).start();
}
Thread t = new MyThread();
t.setDaemon(true);
t.start();
}
static void download( URL url, String file)
throws IOException
{
try(InputStream input = url.openStream();
OutputStream output = new FileOutputStream(file))
{
byte[] data = new byte[1024];
int length;
while((length=input.read(data))!=-1){
output.write(data,0,length);
}
}
}
}
class MyThread extends Thread {
double x;
public void run() {
while(true)
{
x += new Date().getTime();
print();
}
}
public void print() {
System.out.println(x);
}
}
第九讲 流、文件及基于文本的应用
![](https://i-blog.csdnimg.cn/blog_migrate/5b9f7e6a69a48ac4cdeec841ac3e8b4e.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/97670b9e5850604575a3071823615869.gif)
package week9;
import java.io.*;
import java.awt.*;
//import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
public class Recite extends JFrame {
public Recite() {
}
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel lblWord = new JLabel("word");
JLabel lblMeaning = new JLabel("meaning");
public void init() {
setSize(400, 100);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(lblWord);
getContentPane().add(lblMeaning);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
List<String> words = new ArrayList<>();
List<String> meanings = new ArrayList<>();
int current = 0;
public void start() {
new Thread(() -> {
try {
readAll();
} catch (IOException ex) {
}
new javax.swing.Timer(1000, (e) -> {
lblWord.setText(words.get(current));
lblMeaning.setText(meanings.get(current));
current++;
}).start();
}).start();
}
public void readAll() throws IOException {
String fileName = "College_Grade4.txt";
String charset = "GB2312";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), charset));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() == 0)
continue;
int idx = line.indexOf("\t");
words.add(line.substring(0, idx));
meanings.add(line.substring(idx + 1));
}
reader.close();
}
public static void main(String[] args) {
Recite f = new Recite();
f.init();
f.start();
}
}
College_Grade4.txt文件要放在工程目录下
第十讲 图形用户界面
![](https://i-blog.csdnimg.cn/blog_migrate/eb48eaebeef3a13ee69f70040edb7c1e.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/b13c447eb09190aa1450f5087d4d21ea.gif)
package week10;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.awt.event.ActionEvent;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextArea;
/**
* @Title:BMI计算器
* @author 金色的省略号
* @Description:程序可以计算国际标准和国内标准BMI 体重、身高没有输入,或输入错误,会有错误提示输出
*/
public class BMI extends JFrame {
/**
*
*/
private static final long serialVersionUID = 3166024052981905555L;
/**
* BMI Calculator v1.001
*/
private String DomesticStandardsBMI;
private String internationalStandardsBMI;
private double BMI;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BMI frame = new BMI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public BMI() {
//
setFont(new Font("楷体", Font.BOLD, 21));
setTitle("\u4F53\u91CD\u6307\u6570\u8BA1\u7B97\u5668");
setBounds(new Rectangle(200, 200, 300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 505, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// 身高标签
JLabel lblNewLabel = new JLabel("\u8BF7\u8F93\u5165\u8EAB\u9AD8(m)");
lblNewLabel.setFont(new Font("楷体", Font.BOLD, 18));
lblNewLabel.setSize(new Dimension(4, 0));
lblNewLabel.setBounds(37, 87, 182, 36);
contentPane.add(lblNewLabel);
// 体重标签
JLabel lblkg = new JLabel("\u8BF7\u8F93\u5165\u4F53\u91CD(kg)");
lblkg.setFont(new Font("楷体", Font.BOLD, 18));
lblkg.setSize(new Dimension(4, 0));
lblkg.setBounds(37, 10, 182, 36);
contentPane.add(lblkg);
// TextField
textField = new JTextField();
textField.setBackground(Color.CYAN);
textField.setFont(new Font("楷体", Font.BOLD, 21));
textField.setBounds(37, 42, 420, 47);
contentPane.add(textField);
textField.setColumns(10);
// textField_1
textField_1 = new JTextField(2);
textField_1.setBackground(Color.CYAN);
textField_1.setFont(new Font("楷体", Font.BOLD, 21));
textField_1.setColumns(10);
textField_1.setBounds(37, 122, 420, 47);
contentPane.add(textField_1);
// 按钮btnUtton
JButton btnUtton = new JButton("OK");
btnUtton.setFont(new Font("楷体", Font.BOLD, 21));
btnUtton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// 获取BMI
getBMI();
// 输出BMI
DecimalFormat df = new DecimalFormat("0.00");
String bmi = "体质指数:" + df.format(BMI) + "\n";
if (BMI > -0.0001 && BMI < 0.0001) {
bmi = "";
}
textArea.setLineWrap(true);
textArea.setText(DomesticStandardsBMI + " " + internationalStandardsBMI + "\n" + bmi);
}
});
btnUtton.setBounds(374, 193, 83, 65);
contentPane.add(btnUtton);
// textArea
textArea = new JTextArea();
textArea.setFont(new Font("楷体", Font.BOLD, 21));
textArea.setBackground(Color.CYAN);
textArea.setBounds(37, 193, 342, 65);
contentPane.add(textArea);
}
public void getBMI() {
// 判断输入是否正确
String w = textField.getText();
String h = textField_1.getText();
if (!w.matches("^[0-9]+\\.?[0-9]+$") || !h.matches("^[0-9]+[.]?[0-9]+$"))
{
BMI = 0.0;
DomesticStandardsBMI = "请正确输入:";
internationalStandardsBMI = "体重和身高。";
return;
}
// 计算BMI
double weight = Double.valueOf(textField.getText());
double high = Double.valueOf(textField_1.getText());
BMI = weight / Math.pow(high, 2);
if (BMI < 18.5) {
internationalStandardsBMI = "国际标准:偏瘦";
DomesticStandardsBMI = "国内标准:偏瘦";
} else if (BMI < 25) {
internationalStandardsBMI = "国际标准:正常";
if (BMI < 24) {
DomesticStandardsBMI = "国内标准:正常";
} else {
DomesticStandardsBMI = "国内标准:偏胖";
}
} else if (BMI < 30) {
internationalStandardsBMI = "国际标准:偏胖";
if (BMI < 28) {
DomesticStandardsBMI = "国内标准:偏胖";
} else {
DomesticStandardsBMI = "国内标准:肥胖";
}
} else {
internationalStandardsBMI = "国际标准:肥胖";
DomesticStandardsBMI = "国内标准:肥胖";
}
}
}
第十一讲 网络、多媒体和数据库编程
![](https://i-blog.csdnimg.cn/blog_migrate/5054685a0b31e0cf484566c8b3c75dc4.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/67c0fd1fb24ebe161518ae98146549a5.gif)
package week11;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextArea;
//MyBank
public class MyBank extends JFrame{
private Bank bank = new Bank("我的银行");
private String selectBusiness = "开户";
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextArea textArea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyBank frame = new MyBank();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyBank() {
//
setFont(new Font("楷体", Font.BOLD, 21));
setTitle("银行模拟系统");
setBounds(new Rectangle(200, 200, 300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 458, 282);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//
JLabel lblNewLabel = new JLabel("请输入密码");
lblNewLabel.setFont(new Font("楷体", Font.BOLD, 14));
lblNewLabel.setSize(new Dimension(4, 0));
lblNewLabel.setBounds(216, 22, 81, 36);
contentPane.add(lblNewLabel);
//
JLabel lblkg = new JLabel("请输入账号");
lblkg.setFont(new Font("楷体", Font.BOLD, 14));
lblkg.setSize(new Dimension(4, 0));
lblkg.setBounds(10, 22, 81, 36);
contentPane.add(lblkg);
//TextField
textField = new JTextField();
textField.setBackground(Color.CYAN);
textField.setFont(new Font("楷体", Font.BOLD, 21));
textField.setBounds(92, 20, 114, 36);
contentPane.add(textField);
textField.setColumns(10);
//textField_1
textField_1 = new JTextField(2);
textField_1.setBackground(Color.CYAN);
textField_1.setFont(new Font("楷体", Font.BOLD, 21));
textField_1.setColumns(10);
textField_1.setBounds(298, 20, 114, 36);
contentPane.add(textField_1);
//按钮btnUtton
JButton btnUtton = new JButton("OK");
btnUtton.setFont(new Font("楷体", Font.BOLD, 21));
btnUtton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String s = selectBusiness;
String _username = textField.getText();
String _password = textField_1.getText();
// textField_1.setText("******");
double _balance = 0.0;
String d = "";
if(textArea.getText().matches("^\\d+(\\.\\d+)?$")){
_balance = Double.valueOf(textArea.getText());
}
else if(!s.equals("查询")){
d = "请清空此栏,输入金额。";
s = "";
}
if(_username.equals("")
||_password.equals("")){
d = "请正确输入账号和密码。";
s = "";
}
switch(s)
{
case "开户":
d = bank.openAccount(_username,_password,_balance);
break;
case "存款":
d = bank.depositAccount(_username,_password,_balance);break;
case "取款":
d = bank.drawAccount(_username,_password,_balance);break;
case "查询":
d = bank.checkAccount(_username,_password); break;
case "":
break;
}
textArea.setText(d);
}
});
btnUtton.setBounds(356, 138, 62, 46);
contentPane.add(btnUtton);
//textArea
textArea = new JTextArea();
textArea.setFont(new Font("楷体", Font.BOLD, 21));
textArea.setBackground(Color.CYAN);
textArea.setBounds(10, 141, 344, 42);
contentPane.add(textArea);
//
JLabel label = new JLabel("请选择业务");
label.setSize(new Dimension(4, 0));
label.setFont(new Font("楷体", Font.BOLD, 14));
label.setBounds(10, 85, 81, 36);
contentPane.add(label);
JRadioButton rdbtnNewRadioButton = new JRadioButton("开户");
rdbtnNewRadioButton.setBounds(102, 90, 72, 23);
contentPane.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setSelected(true);
rdbtnNewRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
selectBusiness = "开户";
}
});
JRadioButton radioButton = new JRadioButton("存款");
radioButton.setBounds(171, 90, 72, 23);
contentPane.add(radioButton);
radioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
selectBusiness = "存款";
}
});
JRadioButton radioButton_1 = new JRadioButton("取款");
radioButton_1.setBounds(250, 90, 63, 23);
contentPane.add(radioButton_1);
radioButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
selectBusiness = "取款";
}
});
JRadioButton radioButton_2 = new JRadioButton("\u67E5\u8BE2");
radioButton_2.setBounds(320, 90, 62, 23);
contentPane.add(radioButton_2);
radioButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
selectBusiness = "查询";
}
});
//ButtonGroup本身不是控件,不能放到容器里
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton);
buttonGroup.add(radioButton_1);
buttonGroup.add(radioButton_2);
buttonGroup.add(rdbtnNewRadioButton);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/6869d12cc71a5e8d005dac53fc766794.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/9fa47dd018debb08519bd9b54593f842.gif)
package week11;
import java.util.ArrayList;
public class Bank {
private String bankName;
//账户列表
private ArrayList<Account> arr;
//构造
Bank(String _bankName)
{
bankName = _bankName;
arr = new ArrayList<>();
}
//开户
String openAccount(String _username,String _password,double _balance)
{
String str = "";
boolean ok = true;
for (Account a : arr) {
// if(a.getUsername().equals(_username)
// &&a.getUpassword().equals(_password)){
if(a.isUsername(_username)
&&a.isPassword(_password)){
ok = false;
break;
}
}
if(ok){
Account a = new Account(_username,_password,_balance);
arr.add(a);
}
str = "存款余额:"+_balance;
if(!ok){
str = "该用户已经存在。";
}
return str;
}
//取款
String drawAccount(String _username,String _password,double _balance)
{
String d = "";
boolean b = true;
for (Account a : arr) {
if(a.isUsername(_username)
&&a.isPassword(_password)){
if(a.withdraw(_balance)){
d = "存款余额:" + a.getBalance();
}
else{
d = "余额不足,存款余额:" + a.getBalance();
}
b=false;
break;
}
}
if(b)d = "用户名或密码错误!";
return d;
}
//存款
String depositAccount(String _username,String _password,double _balance)
{
String d = "";
boolean b = true;
for (Account a : arr) {
if(a.isUsername(_username)
&&a.isPassword(_password)){
a.deposit(_balance);
d = "存款余额:" + a.getBalance();
b=false;
break;
}
}
if(b)d = "用户名或密码错误!";
return d;
}
//查询
String checkAccount(String _username,String _password)
{
String d = "";
boolean b = true;
for (Account a : arr) {
if(a.isUsername(_username)
&&a.isPassword(_password)){
d = "存款余额:" + a.getBalance();
b=false;
break;
}
}
if(b)d = "用户名或密码错误!";
return d;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/89b3be0e2ff205757368986502b2c191.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/c948df8649434bc453ed190b7c1c656a.gif)
package week11;
public class Account {
private String username;
private String password;
private double balance;
//构造
public Account(String _username,String _password,double _balance)
{
username = _username;
password = _password;
balance = _balance;
}
//取款
boolean withdraw(double _balance)
{
if(balance>=_balance)
{
balance-=_balance;
}
else
{
return false;
}
return true;
}
//存款
void deposit(double _balance)
{
balance+=_balance;
}
//
double getBalance()
{
return balance;
}
//
boolean isUsername(String str)
{
return username.equals(str);
}
//
boolean isPassword(String str){
return password.equals(str);
}
}