??xml version="1.0" encoding="utf-8" standalone="yes"?> 1、加载数据库驱动。(JDBC本nq不能直接访问数据库Q它需要依赖于JDBC驱动E序。) 2、与数据库徏立连接。(格式QDriverManager.getConnection("jdbc:mysql://localhostQ或?27.0.0.1Q?端口?数据库名","用户?, "q入数据库的密码");Q?/p> 4、执行查询ƈq回查询l果?/p> 看一下下面的例子?/p> /** public class Tester { public static void main(String[] args) { } q行l果Q? 要注意的是在获得数据库连接时Ҏ你所用的数据库种c选择加蝲的connector。加载方法先连接数据库的jar包放q你的Project的一个Folder内,然后叛_选择build path-----add to build path可以了。第三步创徏的SQL应根据你具体的需要编写? 获得数据库连接还可以通过下面两种ҎQ? // W一U方?br> public Connection getConnection(String driver, String url, String user, // W二U方?br> public Connection openConnection() { W二U方法比较常用,因ؓ做修改的时候不需要对E序q行大的修改Q只要在配置文g中进行增、删、改可以了?/p> 写一下关于数据库表的操作SQLQ内容不重要Q重要的是理解结构和含义哈?/p> //有自增的语句 CREATE TABLE person( /*创徏学生?/ /*创徏评?/ /*创徏学生评?/ /*向Student表增加“入学时间”列 */ /*修改Student中Sage的属?/ /*修改Course表中Cname为唯一?/ /*删除表Student*/ /*** 表的索引 ***/ /*在Student表的Sname列上建立一个聚族烦?/ /*在三个表中徏立唯一索引*/ /*删除Student表中stusname索引*/ /*** 数据查询 ***/ //查询全体学生的详l记?br>select * //查询l过计算的?br>select Sname Q?004-Sage //查询全体学生的姓名、出生年份和所在的院系Q要求用写的字母表C所有系?br>1、select Sname,'year of birth:' birth, 2004-Sage birthday,LOWER(Sdept) departement //查询选修评的学生学?br>select QallQSno //查询选修评的学生学P消除取值重复的行) 二、条件查? //查询全体计算机系的所有学?nbsp; //查询所有年龄在20岁以下的学生姓名和年?br>select Sname Sage //成W有不及格学生的学?br>select distinct Sno //q里不在20?0岁之间的学生姓名、系别、和q龄 //查询在CS、MA、IS学生的姓名和性别 //查询不在CS、MA、IS学生的姓名和性别 //查询学号200215121的学生详l情?br>select * //查询所有姓刘的学生姓名和性别
3、发送查询或更新语句到数据库?/p>
* DriverManager 驱动E序理?nbsp; 在数据库和相应驱动程序之间徏立连?br> * Connection 对象代表与数据库的连接,也就是在已经加蝲的Driver和数据库之间建立q接
* Statement 提供在基层连接上q行SQL语句Qƈ且访问结?br> * ResultSet 在Statement执行SQL语句Ӟ有时会返回ResultSetl果集,包含的是查询的结果集
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
query();
public static void query(){
Connection conn = null;
try {
//1.加蝲数据库驱?br> Class.forName("com.mysql.jdbc.Driver");
//DriverManager 驱动E序理?nbsp; 在数据库和相应驱动程序之间徏立连?br> //2.获得数据库连?br> conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc_db", "root", "1234");
//3.创徏语句
String sql = "select * from UserTbl";
//q回一个执行SQL的句?br> Statement stmt = conn.createStatement();
//q回查询?br> //4.执行语句
ResultSet rs = stmt.executeQuery(sql);
//5.遍历l果?br> while(rs.next()){
int id = rs.getInt(1);
String username = rs.getString(2);
String password = rs.getString(3);
int age = rs.getInt(4);
System.out.println(id+":"+username+":"+password+":"+age);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn!=null){
try { //关闭数据库连?br> conn.close();
} catch (SQLException e) {
conn = null;
e.printStackTrace();
}
}
}
}
}
String password) {
Connection conn = null;
try {
// Class.forName加蝲驱动
Class.forName(driver);
// DriverManager获得q接
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
String driver = "";
String url = "";
String user = "";
String password = "";
Properties prop = new Properties();
Connection conn = null;
try {
// 加蝲属性文?br> prop.load(this.getClass().getClassLoader().getResourceAsStream(
"DBConfig.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
// Class.forName加蝲驱动
Class.forName(driver);
// DriverManager获得q接
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT ,
name VARCHAR(20) NOT NULL ,
age INT
) ;
create table Student(
Sno char(9) primary key,/*列玩整性约束条ӞSno是主?/
Sname char(20) unique, /*Sname 取唯一?/
Ssex char(2),
Sage smallint,
Sdept char (20),
);
create table Course(
Cno char(4) primary key, /*列表完整性约束条ӞCno是主?/
Cname char(40),
Cpno char(4), /*Cpno的含义是先修?/
Ccredit smallint,
foreign key (Cpno) references Course(Cno)
/*表完整性的U束条gQCpno是外码,被参照表是CourseQ被参照列式Cno*/
);
create table SC(
Sno char (9),
Cno char(4),
Grade smallint,
primary key(Sno,Cno),/*ȝ׃个属性构成,必须作ؓ表完整性进行定?/
foreign key (Sno) references Student(Sno),/*表完整性约束条ӞSno是外码,被参照表是Student*/
foreign key (Cno) references course(Cno),/*表完整性约束条ӞSno是外码,被参照表是Student*/
);
alter table Student add S_entrance date;
alter table Student alter column Sage int;
alter table Course add unique (Cname);
Drop Table Student CascadeQ(cascade 删除表是该表没有限制条gQ在删除基本表的同时Q相关的依赖对象,例如 视图{,都被删除
restrict删除的表不能被其他约束所引用Q不能有视图Q触发器。存储过E或函数{?Q?
create cluster intdex Stusname on Student(Sname);
create unique index Stuno on Student(Sno);
create unique index Coucno on Course(Cno);
create unique index SCno on SC(Sno ASC, Cno DESC);
drop index Student;
一、普通查?
from Student;
from Student;
from Student;
2、select Sname,'year of birth:', 2004-Sage ,LOWER(Sdept)
from Student;
from SC;
select distinct Sno
from SC;
select Sname
from Student
where Sdept='CS';
from Student
where Sage<20;
from SC
where Grade<60;
select Sname,Sdept,Sage
from Student
where Sage not between 20 and 23;
select Sname,Ssex
from Student
where Sdept in('CS','MA','IS');
select Sname,Ssex
from Student
where Sdept not in('CS','MA','IS');
from Student
where Sno like '200215121'; Qlike 可用=替换Q?
select *
from Student
where Sname like '?'; Q? {符L含义Q?br>//删除q龄大于25岁的
delete from Student where age>25;
]]>
代码Q?/p>
class MyThread4 implements Runnable{
private int ticket = 8;//定义8张票
public void run(){
for(int i=0;i<100;i++){
if(this.ticket>0){
try{
Thread.sleep(100);
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"L?+
"==>On sael#######"+(ticket--));
}
}
}
}
public class Tongbukuai {
public static void main(String [] args){
MyThread4 mt = new MyThread4();//׃n同一资源
Thread t1 = new Thread(mt);//
Thread t2 = new Thread(mt);//三个U程代表三个售票H口
Thread t3 = new Thread(mt);//
t1.start();
t2.start();
t3.start();
}
}
q行l果Q?
q怎么可以Q?号和1L口卖Z两张8LQ而且卖出的票的L是不正常的。这是因为多个线E同时进入取的循环Q而程序还没来得及把票数减一Q后面的0号和-1L的出现是因ؓ当ticket Cؓ1的时?受?号和2号三个线E进入@环里Q?号取得了1LQ此时应该停止买了Q但?受?LE还在@环里Q所以就依次取出?号和-1L?
q种情况的处理办法就是ؓ资源加上一把“锁”。每ơ只允许一个线E进入,当前的线E结束操作后才允怸一个线E进入。实现加同步锁的操作有两U方法:1、同步块 2、同步方法。两U方法都要用到synchronized关键字?
代码及运行结果如下:
同步块:
class MyThread4 implements Runnable{
private int ticket = 8;//定义8张票
public void run(){
for(int i=0;i<8;i++){
synchronized(this){
if(this.ticket>0){
try{
Thread.sleep(100);
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"L?+
"==>On sael#######"+(ticket--));
}
}
}
}
}
public class Tongbukuai {
public static void main(String [] args){
MyThread4 mt = new MyThread4();//׃n同一资源
Thread t1 = new Thread(mt);//
Thread t2 = new Thread(mt);//三个U程代表三个售票H口
Thread t3 = new Thread(mt);//
t1.start();
t2.start();
t3.start();
}
}
q行l果Q?
同步ҎQ?
class MyThread4 implements Runnable{
private int ticket = 8;//定义8张票
public void run(){
for(int i=0;i<8;i++){
try{
Thread.sleep(100);
}catch(Exception e){}
this.sale();
}
}
public synchronized void sale(){
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"L?+this.ticket--+"L");
}
}
}
}
public class Tongbukuai {
public static void main(String [] args){
MyThread4 mt = new MyThread4();//׃n同一资源
Thread t1 = new Thread(mt);//
Thread t2 = new Thread(mt);//三个U程代表三个售票H口
Thread t3 = new Thread(mt);//
t1.start();
t2.start();
t3.start();
}
}
q行l果Q?/p>
注意synchronized的位|,不要N位置哦!
我的q个放错了= =Q!
class MyThread4 implements Runnable{
private int ticket = 8;//定义8张票
public void run(){
synchronized(this){ //一个窗口全部卖?br> for(int i=0;i<8;i++){
if(this.ticket>0){
try{
Thread.sleep(100);
}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"L?+"==>On sael#######"+(ticket--));
}
}
}
}
}
public class Tongbukuai {
public static void main(String [] args){
MyThread4 mt = new MyThread4();//׃n同一资源
Thread t1 = new Thread(mt);//
Thread t2 = new Thread(mt);//三个U程代表三个售票H口
Thread t3 = new Thread(mt);//
t1.start();
t2.start();
t3.start();
}
}
看看l果Q?
虽然没卖重号的票Q也没多卖出0?1LQ但是却全都是一个窗?-0L口卖出去的。因为在ti也就?LEstart的时候调用run()ҎQ然?号就悲剧的被错位的synchronized锁在了里面,所以只能一个窗口全部卖完了?
提醒一下大Ӟ不要犯类似的错误?
U程本n的数据通常只有寄存器数据和E序执行时的堆栈D,所以线E的切换比进E的负担要小。线E不能自动运行,必须跻n在某一q程中,pE触发。一个进E可以有多个U程且进E间不共用线E?/p>
实现多线E有两种ҎQ一是承Threadc,二是实现Runnable接口?/p>
l承Threadcd建线E时Q首先要定义一个Threadcȝ子类Qƈ在该子类中重写runQ)Ҏ。runQ)Ҏ是线E体Q说明该U程的具体操作。需要创建线E时Q只需创徏该子cȝ对象在调用其startQ)Ҏ卛_?/p>
实现Runnable接口创徏U程必须重写该接口的runQ)ҎQRunnable接口只有一个runQ)ҎQ?/p>
׃Java是单l承语言Q不直接支持多承,如果一个类已经是其他类的子c,׃能在l承ThreadҎ使该cL为线E类Q这时就要采用实现Runnable接口的方式?/p>
两种Ҏ创徏的线E中h相同目标对象的线E可以共享内存单元,但是实现Runnable接口的线E去创徏目标对象的类可以是某个特定类的子c,因此实现Runnable接口创徏U程比承Threadcd建线E更灉|?/p>
丑և个小例子来看一下哈
l承Threadcd现的多线E:
class MyThread1 extends Thread{
private String name;
public MyThread1(String name){
this.name= name;
}
public void run(){
for(int i=0;i<15;i++){
System.out.println(this.name+"---->Is Running");
}
}
}
public class ThreadDemo01{
public static void main(String[] args){
Runnable r1 = new MyThread1("U程A");
Runnable r2 = new MyThread1("U程B");
Runnable r3 = new MyThread1("U程C");
Runnable r4 = new MyThread1("U程D");
Thread t1 = new Thread (r1);
Thread t2 = new Thread (r2);
Thread t3 = new Thread (r3);
Thread t4 = new Thread (r4);
t1.start();
t2.start();
t3.start();
t4.start();
//也可以这样写
/* MyThread mt1 = new MyThread("U程A");
MyThread mt2 = new MyThread("U程B");
MyThread mt3 = new MyThread("U程C");
MyThread mt4 = new MyThread("U程D");
mt1.start();
mt2.start();
mt3.start();
mt4.start();*/
}
}
0.0Q!q行l果好长Q就不截图了哈,可以自己试试?/p>
实现Runnable接口的多U程Q实C׃n资源Q:
class MyThread2 implements Runnable{
//定义十张?/p>
private int ticket=10;
public void run(){
for(int i=0;i<500;i++){
if(this.ticket>0){
System.out.println("卖票-------"+(this.ticket--));
}
}
}
}
public class ThreadDemo02 {
public static void main(String[] args){
MyThread2 mt =new MyThread2();
//׃n同一资源
Thread mt1 = new Thread(mt);
Thread mt2 = new Thread(mt);
Thread mt3 = new Thread(mt);
mt1.start();
mt2.start();
mt3.start();
}
}
q行l果Q?
]]>Ҏ的类型可以从三个角度q行分类?/p>
按数据流的方向不同可以分入流和输出流。(以程序的角度考虑Q?/p>
按处理数据的单位不同分ؓ字节(以byte为单?位)和字W流Q?6位)?/p>
按功能的不同可以分ؓ节点和处理?/p>
下表中的是输入输出的抽象c,是不能进行实例化的?/p>
以下的是上面抽象cL较常用的的子c,在实现父cL法的同时都定义了自nҎ的功能?/p>
FileInputStream/FileOutputStream//以File开_节点,用来操作文gQ字节流?/p>
FileReader\FileWriter //以File开_处理,用来操作文gQ字W流?/p>
BufferedInputStream/BufferedOutputStream//带缓冲的Q处理流Q字节流?/p>
BufferedReader\BufferedWriter //带缓冲的Q处理流Q字W流?/p>
不难看出以Streaml尾的是字节,以Reader、Writerl尾的是字符?/p>
~冲要套接在相应的节点上Q将d的数据先攑֜内存中进行缓存,提高了镀锡效率,同时扩展了一些方法。用flushҎ可以使内存中数据立刻写出?/p>
处理要套接在节Ҏ或者处理流上,通过Ҏ据的处理增强E序的读写功能?/p>
举一部分例子Q?
用File创徏文g
1.
import java.io.File;
import java.io.IOException;
public class IODemo1 {
public static void main(String[] args) throws IOException{
File f = null;
f = new File("f:"+File.separator+"demo.txt");//或写?"f:\\demo.txt")
System.out.println(f.createNewFile());//当不存在h此抽象\径名指定名称的文件时Q创Z个新的空文g?br> System.out.println(f.getPath());//获取文g目录
System.out.println(f.isDirectory());//判断文g是否是一个目?br> }
}
q行l果
2.
import java.io.File;
public class IODemo2 {
public static void main(String[] args){
File f = null;
f = new File("f:"+File.separator+"demo01.txt");
if(f.exists()){//如果文g存在则删?br> f.delete();
}
else{
try{
System.out.println(f.createNewFile()+"文g已创?);//文g不存在则创徏
}catch(Exception e){}
}
}
}
q行l果提示文g已创建?
3.
import java.io.File;
public class IODemo3 {
public static void main(String[] args){
File f = new File("F:");
File file[] = f.listFiles();//F盘的文g和目录名存在数组?br> for(int i=0;i<file.length;i++){
System.out.println(file[i]);
}
String str[] = f.list();//F盘的文g存在数组?br> for(int i=0;i<str.length;i++){
System.out.println(str[i]);
}
}
}
?nbsp; F盘文件太多了Q就不截图了哈,可以自己试一下!^_^
InputStream的例子:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class IODemo8 {
public static void main(String[] args) {
File f = new File("e:" + File.separator + "demo.txt");// 要输入到的文?br> InputStream input = null;
try {
input = new FileInputStream(f);
} catch (Exception e) {
}
byte b[] = new byte[9];
for (int i = 0; i < b.length; i++) {
try {
b[i] = (byte) input.read();
} catch (Exception e) {
}
}
try {
input.close();
} catch (Exception e) {
}
// 输出d的内?br> System.out.println(new String(b));
}
}
因ؓ定义的数l长度是1024Q所以后面跟了N多个I格?
FileInputStrea的例子:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IODemo13 {
public static void main(String[] args){
int b=0;
FileInputStream in = null;
try{
in = new FileInputStream("e:"+File.separator+"demo1.txt");
}catch(FileNotFoundException e){
e.printStackTrace();
}
long num = 0;
try{
while((b=in.read())!=-1){//到文件尾得到-1Q结束@?br> System.out.print((char)b);
num++;
}
in.close();
}catch(IOException e){e.printStackTrace();}
System.out.println("p取了"+num+"个字?);
}
}
Reader的例子:
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public class IODemo11 {
public static void main(String[] args){
File f=new File("e:"+File.separator+"demo.txt");
Reader r =null;
try{
r = new FileReader(f);
}catch(Exception e){}
char c[] = new char[1024];
int count = 0;
try{
count = r.read(c);
}catch(Exception e){}
System.out.println(new String(c,0,count));
}
}
q行l果^_^
FileWriter的例子:
import java.io.File;
import java.io.FileWriter;
public class IODemo12 {
public static void main(String[] args){
File f =new File("e:"+File.separator+"demo02.txt");//要写入到的文?br> FileWriter out = null;
try{
out = new FileWriter(f);
}catch(Exception e){}
try{
out.write("Hello fly?);//写入的内?br> }catch(Exception e){}
try{
out.close();
}catch(Exception e){}
}
}
?q个在E盘生成了一个文件demo02Q里面有以句话Hello fly—?
BufferedReader的例子:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class IODemo17 {
public static void main(String[] args){
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(System.in));//从键盘获取输入的内容
String str = null;
System.out.print("误入内容:");
try{str = buf.readLine();//d输入的内?br> buf.close();
}catch(Exception e){}
System.out.println("输入的内容:"+str);
}
}
׃Dq些例子吧!有错的请指出来哈^_^Q?/p>
q行E序昄l果如下Q?/p>
1、添加记录:
2、修改记录:
3、浏览记录:
4、退出系l:
各类之间调用关系如下图所C:
E序代码如下Q?/p>
import com.dr.demo.menu.Menu;
public class Main {
public static void main(String[] args) {
new Menu();
}
}
public class Menu {
InputData input = null;
public Menu(){
this.input = new InputData();
//循环出现菜单
while(true){
this.show();
}
}
//要定义的菜单的内?br> public void show(){
System.out.println("\t\t\t\t1~增加人员信息");
System.out.println("\t\t\t\t2~修改人员信息");
System.out.println("\t\t\t\t3~览人员信息");
System.out.println("\t\t\t\t4~退出本pȝQ?);
System.out.println("\n\n请选择要用的操作Q(1.2.3.4Q?);
int temp = input.getInt();
switch(temp){
case 1:{//增加人员信息
new PersonOperate().add();//业务处理?br> break;
}
case 2:{//修改人员信息
new PersonOperate().update();
break;
}
case 3:{//览人员信息
new PersonOperate().show();
break;
}
case 4:{//退出系l?br> System.out.println("选择的是退出本pȝQ?);
System.out.println("成功退出本pȝQ?);
System.exit(1);
}
default:{
System.out.println("输入的内容不正确Q请重新输入Q?);
break;
}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputData {
public BufferedReader buf = null;
public InputData(){
buf = new BufferedReader(new InputStreamReader(System.in));
}
public String getString(){
String str = null;
try {
str = buf.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public int getInt(){
int temp = 0;
String str = null;
boolean flag = true;
while(flag){
//输入数据
str = this.getString();
if(!(str.matches("\\d+"))){
//输入的不?-4的数Q提C重新输?br> System.out.println("输入的数字有误,请重新输入!Q必L整数1-4Q?);
}
else {//数据输入正确Q进行{?br> temp = Integer.parseInt(str);
//退出@?br> flag = false;
}
}
return temp;
}
public String getpsString(){
String str = null;
try {
str = buf.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public float getFloat(){
float f = 0;
String str = null;
boolean flag = true;
while(flag){
str = this.getString();
if(!(str.matches("\\d+?.\\d{1,2}"))){
//如果输入的不是两位的数则提C重新输?br> System.out.println("输入的数必须是floatcdQ请重新输入Q?);
}
else{
f = Float.parseFloat(str);
flag = false;//退出@环哈
}
}
return f;
}
}
public class PersonOperate {
private InputData input = null;
public PersonOperate(){
this.input = new InputData();
}
//增加记录
public void add(){
String name = null;
int age = 0;
String position = null;
float salary = 0;
System.out.println("误入姓名:");
name = this.input.getString();
System.out.println("误入年龄:");
age = this.input.getInt();
System.out.println("误入职位:");
position = this.input.getpsString();
System.out.println("误入薪酬:");
salary = this.input.getFloat();
//生成对象q保存在文g?br> Person p = new Person(name,age,position,salary);
try{
new FileOperate().save(p);//IO操作?br> System.out.println("数据保存成功Q?);
}catch(Exception e){
System.out.println("数据保存p|Q?);
}
}
//览记录
public void show(){
Person p = null;
try{
p = (Person)new FileOperate().read();
}catch(Exception e){
System.out.println("昄数据p|Q请查数据是否存在!");
}
if(p!= null){
System.out.println(p);
}
}
//修改记录
public void update(){
Person p = null;
try{
p = (Person)new FileOperate().read();
}catch(Exception e){
System.out.println("昄数据p|Q请查数据是否存在!");
}
if(p!=null){
String name = null;
int age = 0;
String position = null;
float salary = 0.0f;
System.out.println("误入新姓名Q(原姓名:"+p.getName()+"Q?);
name = this.input.getString();
System.out.println("误入新q龄Q(原年?+p.getAge()+"Q?);
age = this.input.getInt();
System.out.println("误入新职位Q(原职?+p.getPosition()+"Q?);
position = this.input.getpsString();
System.out.println("误入新工资Q(原工?+p.getSalary()+"Q?);
salary = this.input.getFloat();
//信息重置
p.setName(name);
p.setAge(age);
p.setPosition(position);
p.setSalary(salary);
try{
new FileOperate().save(p);
System.out.println("数据更新成功Q?);
}catch(Exception e){
System.out.println("数据更新p|Q?);
}
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FileOperate {
public static final String FILENAME = "e:"+File.separator+"person.ser";
//把对象保存在文g?br> public void save(Object obj){
ObjectOutputStream out = null;
try{
out = new ObjectOutputStream(new FileOutputStream(new File(FILENAME)));
//写入对象
out.writeObject(obj);
}catch(Exception e){
try{
throw e;
}catch(Exception e1){}
}finally{
try{
out.flush();
out.close();
}catch(Exception e){}
}
}
//从文件中d对象
public Object read() throws Exception{
Object obj = null;
ObjectInputStream input =null;
try{
input = new ObjectInputStream(new FileInputStream(new File(FILENAME)));
obj = input.readObject();
}catch(Exception e){
throw e;
}finally{
try{
input.close();
}catch(Exception e){}
}
return obj;
}
}
import java.io.Serializable;
public class Person implements Serializable{
public String toString(){
return "姓名Q?+this.name+"\tq龄Q?+this.age+" \t职位Q?+this.position+"\t薪酬Q?+this.salary;
}
private String name;
private int age;
private String position;
private float salary;
public Person(){}
public Person(String name,int age,String position,float salary){
this.name = name;
this.age = age;
this.position = position;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
本程序优点在于各层之间耦合性不大,独立性比较强Q重在理解Menu层、文件操作层、IO操作层三层之间的调用关系。存在的~陷希望读者可以完善?/p>
上面的只是比较常用的一部分Qƈ不全面,Ƣ迎你补充。有错误的话h出来哈?
1.病h挂号使用的客LQ在界面上选择想选择的专家对应的专家P屏幕上提C挂h功,同时该病hdC所选的专家对应的病人队列中?/p>
2.医院工作人员使用的客LQ在界面上单ȝ应的专家号就会在其对应的病h队列中取Z位病人,在屏q上昄该病人对应的id和名字(防止出现重名的尴)q提C到对应的专家处p。当没有病hӞ做出提示?/p>
装ȝc?
public class Doctor {
private String ID;
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
}
装病hc?
public class Patient {
private String id;
private String name;
private String doctorID;//病h选择的专家的ID
public String getDoctorID() {
return doctorID;
}
public void setDoctorID(String doctorID) {
this.doctorID = doctorID;
}
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
挂号服务器类
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class Hospitalserver {
public Map<String,Queue<Patient>> specialistList = new HashMap<String,Queue<Patient>>();
Queue<Patient> doc1Queue = new LinkedList<Patient>();
Queue<Patient> doc2Queue = new LinkedList<Patient>();
Queue<Patient> doc3Queue = new LinkedList<Patient>();
List<Patient> allPatient = new LinkedList<Patient>();
public void init(){
//实例化三个医生,其ID是对应的专家号
Doctor doc1 = new Doctor();
doc1.setID("01");
Doctor doc2 = new Doctor();
doc2.setID("02");
Doctor doc3 = new Doctor();
doc3.setID("03");
//实例?个病?q添加到对应的专安列中
Patient aa = new Patient();
aa.setid("001");
aa.setName("joe a");
aa.setDoctorID("01");
doc1Queue.add(aa);
Patient bb = new Patient();
bb.setid("002");
bb.setName("joe b");
aa.setDoctorID("01");
doc1Queue.add(bb);
//********************************************
Patient cc = new Patient();
cc.setid("003");
cc.setName("joe c");
aa.setDoctorID("02");
doc2Queue.add(cc);
Patient dd = new Patient();
dd.setid("004");
dd.setName("joe d");
aa.setDoctorID("02");
doc2Queue.add(dd);
//********************************************
Patient ee = new Patient();
ee.setid("005");
ee.setName("joe e");
aa.setDoctorID("03");
doc3Queue.add(ee);
Patient ff = new Patient();
ff.setid("006");
ff.setName("joe f");
aa.setDoctorID("03");
doc3Queue.add(ff);
specialistList.put(doc1.getID(), doc1Queue);
specialistList.put(doc2.getID(), doc2Queue);
specialistList.put(doc3.getID(), doc3Queue);
}
}
病h使用的客L
import java.util.Queue;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class HospitalPatientUI {
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setMaximized(true);
shell.setText("医院排队之病Z用的客户度端");
// ------------------新插入的界面核心代码------------------------
Hospitalserver hospatient = new Hospitalserver();// 实例化类
hospatient.init();// 初始化队列服务器
final Queue<Patient> doc1Queue = hospatient.specialistList.get("01");
final Queue<Patient> doc2Queue = hospatient.specialistList.get("02");
final Queue<Patient> doc3Queue = hospatient.specialistList.get("03");
final Text patient1Txt = new Text(shell, SWT.MULTI);
patient1Txt.setBounds(100, 50, 200, 150);
final Button patient1button = new Button(shell, SWT.Activate);
patient1button.addSelectionListener(new SelectionAdapter() { // 加一个选择监听?br> public void widgetSelected(SelectionEvent e) {
//实例化一个病人,q添加到他选择的专家的队列?br> Patient patient1 = new Patient();
doc1Queue.add(patient1);
patient1Txt.setText("Ƣ迎您选择一号专家\n请在{待区稍{\n另外请关注广播和屏幕通知Q?);
}
});
patient1button.setBounds(100, 330, 200, 75); // 讄按钮位置
patient1button.setFont(new Font(display, "宋体", 12, SWT.BOLD));
patient1button.setText("一号专?);// 讄按钮上的文字
// *****************************************************************
final Text patient2Txt = new Text(shell, SWT.MULTI);
patient2Txt.setBounds(400, 50, 200, 150);
final Button patient2button = new Button(shell, SWT.Activate);
patient2button.addSelectionListener(new SelectionAdapter() { //
public void widgetSelected(SelectionEvent e) {
Patient patient2 = new Patient();
doc1Queue.add(patient2);
patient2Txt.setText("Ƣ迎您选择二号专家\n请在{待区稍{\n另外请关注广播和屏幕通知Q?);
}
});
patient2button.setBounds(400, 330, 200, 75); // 讄按钮位置
patient2button.setFont(new Font(display, "宋体", 12, SWT.BOLD));
patient2button.setText("二号专家");// 讄按钮上的文字
// ***************************************************
final Text patient3Txt = new Text(shell, SWT.MULTI);
patient3Txt.setBounds(700, 50, 200, 150);
final Button patient3button = new Button(shell, SWT.Activate);
patient3button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Patient patient3 = new Patient();
doc1Queue.add(patient3);
patient3Txt.setText("Ƣ迎您选择三号专家\n请在{待区稍{\n另外请关注广播和屏幕通知Q?);
}
});
patient3button.setBounds(700, 330, 200, 75); // 讄按钮位置
patient3button.setFont(new Font(display, "宋体", 13, SWT.BOLD));
patient3button.setText("三号专家");// 讄按钮上的文字
// ------------------END---------------------------------------------
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
q行l果Q?
医院工作人员使用的客LQ?
import java.util.Queue;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class HospitalWorkerUI {
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setMaximized(true);
shell.setText("医院排队之医院工作h员用的客户?);
// ------------------新插入的界面核心代码------------------------
Hospitalserver qs = new Hospitalserver();//实例化类
qs.init();//初始化队列服务器
final Queue<Patient> doc1Queue=qs.specialistList.get("01");
final Queue<Patient> doc2Queue=qs.specialistList.get("02");
final Queue<Patient> doc3Queue=qs.specialistList.get("03");
final Text doc1Txt = new Text(shell,SWT.MULTI);
doc1Txt.setBounds(100, 50, 200, 150);
final Button doc1button = new Button(shell, SWT.Activate);
doc1button.addSelectionListener(new SelectionAdapter() { // 加一个选择监听?br> public void widgetSelected(SelectionEvent e) {
Patient one=doc1Queue.poll();
if(one!=null)
{
doc1Txt.setText("?+one.getid()+"L?+one.getName()+"C号专家处pQ请其他病hE等?);
}
else
{
doc1Txt.setText("暂时没有病h了,hE作休息?);
}
}
});
doc1button.setBounds(100, 330, 200, 75); // 讄按钮位置
doc1button.setFont(new Font(display,"宋体",12,SWT.BOLD));
doc1button.setText("一号专?);// 讄按钮上的文字
//*****************************************************************
final Text doc2Txt = new Text(shell,SWT.MULTI);
doc2Txt.setBounds(400, 50, 200, 150);
final Button doc2button = new Button(shell, SWT.Activate);
doc2button.addSelectionListener(new SelectionAdapter() { // 加一个�?择监听器
public void widgetSelected(SelectionEvent e) {
Patient two=doc2Queue.poll();
if(two!=null)
{
doc2Txt.setText("?+two.getid()+"L?+two.getName()+"请到二号专家处就诊,请其他病人稍{?);
}
else
{
doc2Txt.setText("暂时没有病h了,hE作休息?);
}
}
});
doc2button.setBounds(400, 330, 200, 75); // 讄按钮位置
doc2button.setFont(new Font(display,"宋体",12,SWT.BOLD));
doc2button.setText("二号专家");// 讄按钮上的文字
//***************************************************
final Text doc3Txt = new Text(shell,SWT.MULTI);
doc3Txt.setBounds(700, 50, 200, 150);
final Button doc3button = new Button(shell, SWT.Activate);
doc3button.addSelectionListener(new SelectionAdapter() { // 加一个�?择监听器
public void widgetSelected(SelectionEvent e) {
Patient three=doc3Queue.poll();
if(three!=null)
{
doc3Txt.setText("?+three.getid()+"L?+three.getName()+"请到三号专家处就诊,请其他病人稍{?);
}
else
{
doc3Txt.setText("暂时没有病h了,hE作休息?);
}
}
});
doc3button.setBounds(700, 330, 200, 75); // 讄按钮位置
doc3button.setFont(new Font(display,"宋体",13,SWT.BOLD));
doc3button.setText("三号专家");// 讄按钮上的文字
// ------------------END---------------------------------------------
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
q行l果Q?
不之处Q没有实现自动判断病人选择的专家号Q没有实现病Z用的客户端和医院工作人员使用的客L的同步更新。当然还有一些其他的不Q期待您指出q提出完善意见?
1.银行工作人员使用的客L实现功能Q每ơ单击Button“下一个”,H口上会昄提示X号顾客去yL口办理业务;当顾客队列里没有֮时对工作人员作出提示?/p>
2.֮使用的客L实现功能Q每当有֮单击Button“个Z务”,H口上会昄当前֮在队伍中的位|以及他的前面还有多位֮Q当排在当前֮前面的顾客h数超q?0人时提示前面已经?0个hQ是否l等候。关于这个金卡通道嘛,现在行各种会员啊VIP啦等{,q个金卡通道当然是为银行的VIP准备的。当单击Button“金卡通道”时Q将当前Waiterd到顾客队列的首位q在H口上显C无需{待~~?/p>
代码如下Q?/p>
装֮cR?/p>
public class Waiter {
private int num; //֮?br> private int frontNum; //排在前面的h?br> private int flag; //卡类?
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getFrontNum() {
return frontNum;
}
public void setFrontNum(int frontNum) {
this.frontNum = frontNum;
}
}
初始化顾客队列(30个hQ?
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class QueueServer {
LinkedList<Waiter> waiterList = new LinkedList<Waiter>();
public LinkedList<Waiter> init(){
for(int i=1;i<=30;i++){
Waiter w = new Waiter();
w.setNum(i);
w.setFrontNum(i-1);
waiterList.offer(w);
}
return waiterList;
}
}
֮使用的客LQ?
import java.util.LinkedList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Swtgoldcard {
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setMaximized(true);
shell.setText("银行排队pȝ之金卡插?);
// ------------------新插入的界面核心代码------------------------
QueueServer qs = new QueueServer();//实例化顾客队列类
final LinkedList<Waiter> waiterList = qs.init();//初始化队列服务器
final Text txt = new Text(shell,SWT.MULTI);
txt.setBounds(40, 50, 500, 450);
final Button button = new Button(shell, SWT.Activate);
button.addSelectionListener(new SelectionAdapter() { // 加一个选择监听?br> public void widgetSelected(SelectionEvent e) {
//System.out.println("############### " + waiterList.size());
Waiter waiter = new Waiter();
waiter.setNum(waiterList.size()+1);
waiter.setFrontNum(waiterList.size());
waiterList.offer(waiter);
if(waiterList.size() <= 50){
txt.setText( "您现在排?+waiter.getNum()+"位置上\n您前面有"+waiter.getFrontNum()+"个h\nh耐心{候!");
}else{
txt.setText("您前面已l排50个h\n误虑是否l箋{待Q\n"+"您现在排?+waiter.getNum()+"位置上\n您前面有"+waiter.getFrontNum()+"个h\nh耐心{候!");
}
}
});
button.setBounds(180, 530, 200, 75); // 讄按钮位置
button.setFont(new Font(display,"宋体",12,SWT.BOLD));
button.setText("个h业务");// 讄按钮上的文字
//金卡通道
final Text goldTxt = new Text(shell,SWT.MULTI);
goldTxt.setBounds(900, 50, 500, 450);
final Button goldButton = new Button(shell, SWT.Activate);
goldButton.addSelectionListener(new SelectionAdapter() { // 加一个选择监听?br> public void widgetSelected(SelectionEvent e) {
Waiter goldWaiter = new Waiter();
goldWaiter.setFlag(1);
waiterList.addFirst(goldWaiter);
goldTxt.setText("您是金卡用户Q|可以优先接受服务Q|无需{待Q\n"+"您现在排?+goldWaiter.getNum()+"位置上,\n您前面有"+goldWaiter.getFrontNum()+"个h");
}
});
goldButton.setBounds(1060, 530, 200, 75); // 讄按钮位置
goldButton.setFont(new Font(display,"宋体",12,SWT.BOLD));
goldButton.setText("金卡通道");// 讄按钮上的文字
// ------------------END---------------------------------------------
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
q行l果Q?
当等待队列中人数过50人时昄l果Q?
银行工作人员使用的客LQ?
import java.util.Queue;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class BankWorkerUI {
public static void main(String[] args) {
final Display display = Display.getDefault();
final Shell shell = new Shell();
shell.setSize(352, 253);
shell.setText("银行排队pȝ之工作h员客L");
// ------------------新插入的界面核心代码------------------------
QueueServer qs = new QueueServer();//实例化类
final Queue<Waiter> waiterList = qs.init();//初始化队列服务器
final Text txt = new Text(shell,SWT.MULTI);
txt.setBounds(65, 30, 220, 70);
final Button button = new Button(shell, SWT.Activate);
button.addSelectionListener(new SelectionAdapter() { // 加一个选择监听?br> public void widgetSelected(SelectionEvent e) {
//System.out.println("############### " + waiterList.size());
Waiter waiter= waiterList.poll();
if(waiter!= null){
txt.setText(waiter.getNum()+"号顾客请?L口办理业?);
}else{
txt.setText("暂时没有֮要办理业务,您可以休息一下!\n ");
}
}
});
button.setBounds(120, 141, 100, 25); // 讄按钮位置
button.setText("下一?);// 讄按钮上的文字
// ------------------END---------------------------------------------
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}
q行l果Q?
q个E序q有~陷Q没有用到数据库Q无法实现工作h员所用的客户端与֮所用的客户端同步更斎ͼ请高手指点完善?
1装?/p>
装性是一U信息隐蔽技术,它体Ccȝ说明Q是对象重要的特性。封装数据和操作该数据的方法(函数Q封装ؓ一个整体,形成独立性很强的模块Q得用户只能看到对象的外部Ҏ(对象可以接受哪些信息Q可以进行何U处理)Q而对象的内部Ҏ(内部private的属性和实现处理能力的算法)用户是看不到的。简a之就是封装对象的设计者和对象的用者分开Q用者只要知道对象可以做什么,无需知道是怎么做出来的。借助装有助于提高类和系l的安全性?/p>
看一下下面的例子Q?/p>
没有装的程序:
class Person{
String name;
int age;
public void say(){
System.out.println(“NAME:***?name+?nbsp; AGE:***?age);
}
}
public class Demo01{
public static void main(String arg[]){
Person p=new Person();
p.name=“Michael?
p.age = ?6;
p.say();
}
}
q行l果Q?
未封装时E序可以通过~译q行也没有问题,但是q龄是不可以值的。这是属性直接对外可见造成的笑话?
装后的E序Q?
class Person{
private String name;
private int age;
public void say(){
System.out.println(“NAME:***?name+?nbsp; AGE:***?age);
}
}
public class Demo02{
public static void main(String arg[]){
Person p=new Person();
p.name=“Michael?
p.age=-26;
p.say();
}
}
q行l果Q?
׃q行了封装,属性对外不可见Q所以编译时提示上图灰色区域中的内容?
对于装的属性的讄和取得应该通过setter和getterҎQ通过Setter和GetterҎ讄装的属性ƈ对年龄D行检查的E序如下Q?
class Person{
private String name;
private int age;
public void setName(String n){
name=n;
}
public String getName(){
return name;
}
public void setAge(int a){ //Setter是入口,Getter是出口,在setterҎ处检查年龄是否在允许的范围内?
if(a>=0&&a<120){
age=a;
}else{
age = -1;
System.out.println("q龄非法");//提示q龄非法;
}
}
public int getAge(){
return age;
}
public void say(){
System.out.println("NAME:***"+name+" AGE:***"+age);
}
}
public class Demo04{
public static void main(String arg[])
{
Person p=new Person();
p.setName("Michael");
p.setAge(-26);
p.say();
}
}
此时q行后提C年龄非法:
Q承?/p>
l承是一U由已有cd建新cȝ机制Q利用承,可以先创Z个共有属性的一般类Q根据这个一般类再创建具有特D属性的新类。新cȝ承一般类的方法ƈҎ需要增加它自己的新Ҏ。有l承而得到的cȝ为子c,被承的cȝ为父c(类Q,当然子类也可以成为父cR如下图Q由下向上看Q双炔R机类和歼Lc都l承了战斗机cȝ特点但又分别h自己新的功能Q同P战斗机类和民用机c都h飞机cL有的特点也都扩展了属于自q新功能。也是说双炔R机和歼击机既h飞机的全部特点又拥有战斗机的全部特点?/p>
用程序说明一下:
class Person{
String name;
int age;
public String getInfo()
{
return "姓名Q?--"+this.name+"\n"+"q龄Q?--"+this.age;
}
}
Q/Studentcȝ承Personc?/p>
class Student extends Person
{
String school;Q/StudentcM扩展的属?br>}
public class Demo01 {
public static void main(String args[])
{
Student s = new Student();
Q/?Person cM为属性赋?nbsp;
s.name = "Michael";
s.age = 25;
Q/?Student cM为属性赋?br> s.school = "Camoridge University " ;
System.out.println(s.getInfo()+"\n"+"学校Q?--"+s.school);
}
}
q行l果如下
Q多态?/p>
同一个信息被不同的对象接收到时可能生完全不同行为,q就是多态性。通过l承q程中的Ҏ重写可以实现多态。多态可以改善程序的l织构架Q提高程序的可读性,也是E序更容易扩充?/p>
用下面的E序说明一下:
class A
{
public void fun1()
{
System.out.println("使用父类Ҏ!");
}
}
class B extends A
{
// 此方法重写父cM的fun1()Ҏ
public void fun1()
{
System.out.println("父类Ҏ已被子类Ҏ重写Q?+"\n"+"使用子类Ҏ");
}
}
public class Overrid
{
public static void main(String args[])
{
A a = new A();
B b = new B();
a.fun1();
b.fun1();
}
}
q行l果如下Q?
同样使用了fun1()ҎQ在父类和子cM产生了完全不同的l果?/p>
在此单说明一下重写和重蝲的区别。重写(OverrideQ是发生在子cd父类之间Qؓ满需要,子类对从父类中承来的方法进行重写,Ҏ的名U和参数cd或个数相同但是子cL法的讉K权限不可以比父类更严根{而重载(OverloadingQ只发生在同一个类中,Ҏ的名U相同,但是参数的个数或者类型不同?/p>