华南理工大学Java语言程序设计课堂作业答案
更新时间:2024-04-15 06:20:01 阅读量: 综合文库 文档下载
homework01(直接跳过吧,一点技术含量都没的。只提取了前面的解法) 2011-02-21 13:59
1. 编写一个类(控制台), 输入你的名字, 回车后, 向屏幕输出信息\欢迎你, ***\类似字样
2. 使用命令行模式编译,执行该程序, 将class文件指定输出到class目录
3. 给类添加 move(), turnLeft(), pickPeeper(), putPeeper() 等方法, 并在Main中调用显示相关信息
4. 给类和各方法添加注释, 并使用javadoc指令输出代码文档
Welcome.java
Homework01
1. 编写一个类(控制台), 输入你的名字, 回车后, 向屏幕输出信息\欢迎你, ***\类似字样;
(Welcome.java)
2. 使用命令行模式编译,执行该程序, 将class文件指定输出到class目录;
(现class文件夹在D:/目录下,控制台命令输入:javac -d D:\\class Welcome.java) 3. 给类添加 move(), turnLeft(), pickPeeper(), putPeeper() 等方法, 并在Main中 调用显示相关信息;
4. 给类和各方法添加注释, 并使用javadoc指令输出代码文档.
(现新建doc文件夹在D:\\下以存储文档,控制台输入:javadoc -d D:\\doc Welcome.java)
homework02
2011-02-27 22:32 修路工:
请使用分附件中的空白项目,装载 sample03_holes_5.w 背景,修缮1st Street。
/*
* File: StoneMasonKarel.java
* --------------------------
* The SampleKarel subclass as it appears here does nothing. */
import stanford.karel.*; /*
* Name:
* Section Leader: */
public class SampleKarel extends SuperKarel { int count = 0;
public void run() {
// You fill in this part while(count < 32){ judgeAndPick(); }
}
if (frontIsBlocked() || rightIsClear()) {
changeDirection(); }
move();
public void changeDirection() {
if (rightIsClear()) { turnRight(); } else { if (leftIsBlocked()) { }
}
if (rightIsBlocked()) {
turnRight(); turnRight(); }
turnRight();
if (rightIsBlocked()) { turnLeft(); }
}
public static void main(String[] args) { String[] newArgs = new String[args.length + 1]; System.arraycopy(args, 0, newArgs, 0, args.length); public void judgeAndPick() { }
if (beepersPresent()) { pickBeeper(); }
count++;
}
}
newArgs[args.length] = \ public String className() { return this.getClassContext()[1].getCanonicalName(); }
}.className();
SuperKarel.main(newArgs);
homework03
2011-03-07 16:07
使用之前的空白项目,装载*collect* .w 背景,收集全部的Beeper. /*
* File: StoneMasonKarel.java * --------------------------
* The SampleKarel subclass as it appears here does nothing. */
import stanford.karel.*;
public class CollectAllBeepers extends SuperKarel {
/**
* Through the maze * @author 黄泽津 */
public void run() { collect();
while(frontIsBlocked()&&!leftIsBlocked()){
if(facingEast()) { turnLeft(); move();
turnLeft(); collect(); }
if(facingWest()) { turnRight();
move();
turnRight(); collect(); } } }
private void collect() { while(beepersPresent()){ pickBeeper(); }
if(frontIsBlocked()) { return; } else move();
collect(); }
public static void main(String[] args) {
String[] newArgs = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 0, args.length); newArgs[args.length] = \ public String className() {
return this.getClassContext()[1].getCanonicalName(); }
}.className();
SuperKarel.main(newArgs); } }
homework04 迷宫收集 2011-03-13 21:47
创建迷宫world并放置一定的Beeper,装载该World后,收集全部的Beeper, 发送时请携带该world地图
int count = 0;
public void run() {
//You fill in this part
while(count < 32){ }
judgeAndPick();
if (frontIsBlocked() || rightIsClear()) { changeDirection(); } move();
}
public void changeDirection() {
if (rightIsClear()) { turnRight(); } else { if (leftIsBlocked()) { turnLeft(); }
}
turnLeft();
}
public void judgeAndPick() { }
if (beepersPresent()) { pickBeeper(); count++; }
homework05 迷宫收集 2011-03-26 21:54
1. 从文件中构造二维世界, 文件为文本模式文件, 由字符'0' '1'组成
2. 构造该世界最下方地平面处的路面曲线, 以简单直观的方式在文本中打印, 路面可用'*'表示
3. 可将Ship, Person的行进路线以以简单直观的方式在各自独立的文本中打印, 行进路线
可用'*'表示
FileMap.java /** *
*/
package map;
import java.io.*; import java.util.*; /**
* @author guhonglueying * */
// map生成方法之从文件中读取
public class FileMap extends SubMap {
} catch (IOException e) { e.printStackTrace(); }
charArr = new char[stk.size()][];
for (int i = charArr.length - 1; i > -1; i--) { }
charArr[i] = stk.pop();
try {
FileReader fr = new FileReader(s[0]);
BufferedReader bw = new BufferedReader(fr); while ((str = bw.readLine()) != null) { stk.push(str.toCharArray()); }
// 重写父类create方法,用于从文件中读取新地图 public void create(String... s) {
String str = null;
Stack
}
}
SimpleMap.java /** *
*/
package map;
/**
* @author guhonglueying * */
// map生成方法之程序中定义map
public class SimpleMap extends SubMap { // 重写父类create方法,用来从程序中创建新地图 }
SubMap.java /** *
*/
package map;
}
charArr = new char[][] { { '0', '0', '1', '1', '1', '0', '0', '0' }, { '1', '0', '0', '0', '0', '0', '1', '0' }, };
{ '0', '0', '0', '1', '1', '0', '1', '0' }, { '0', '1', '0', '0', '0', '0', '0', '0' }, { '0', '1', '0', '1', '0', '1', '0', '0' }, { '0', '0', '0', '1', '0', '0', '0', '1' }, { '1', '1', '0', '0', '0', '1', '0', '1' }, { '1', '1', '1', '1', '1', '1', '0', '0' }
public void create(String... s) {
/**
* @author guhonglueying * */
// 生成map的抽象类,用来定义map的一些public属性和方法 public abstract class SubMap { }
SystemInMap.java /**
* */
package map;
public void setCol(int col) { }
this.col = col; int row; int col;
char[][] charArr;
public void setRow(int row) { this.row = row; }
public int getRow() { return row; }
public int getCol() { }
return col;
// 抽象方法,在子类中实现新地图生成的不同实现 public abstract void create(String... s); public char[][] getMap() { }
this.row = charArr.length; this.col = charArr[0].length; return charArr;
import java.io.*; import java.util.*; /**
* @author guhonglueying * */
// map生成方法之从标准输入流获取
public class SystemInMap extends SubMap {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bw = new BufferedReader(isr); System.out.println(\请用以下字符输入一方形地图:\\n1-墙,0-路,@-入口,#-出口\\n每次输入一行回车,输入E结束\ }
}
while ((str = bw.readLine()) != null) { if (str.equalsIgnoreCase(\ }
break; }
stk.push(str.toCharArray());
// 重写父类create方法,用于从命令操作符中读取新地图 public void create(String... s) {
String str = null;
Stack
} catch (IOException e) { e.printStackTrace(); }
charArr = new char[stk.size()][];
for (int i = charArr.length - 1; i > -1; i--) { charArr[i] = stk.pop(); }
Person.java /** * */
package objectmovable;
import util.*; /**
* @author guhonglueying * */
// 实现person的走迷宫过程
public class Person extends SubObjectMovable { }
public void Maze(char[][] ch) { System.out.println(\ }
h = new Helper(ch);
h.searchTheWay(System.out); h.printTheWay(System.out, 2);
Ship.java /** * */
package objectmovable;
import util.*;
/**
* @author guhonglueying * */
// 实现ship的走迷宫过程
public class Ship extends SubObjectMovable {
public void Maze(char[][] ch) { System.out.println(\
}
}
h = new Helper(ch);
h.searchTheWay(System.out); h.printTheWay(System.out, 1);
SubObjectMovable.java /** * */
package objectmovable;
import util.Helper;
/**
* @author guhonglueying * */
// 接口,以实现不同物体的走迷宫过程
public abstract class SubObjectMovable { Helper h; }
public abstract void Maze(char[][] ch);
Helper.java /** * */
package util;
import java.util.*; import java.io.*; /**
* @author guhonglueying * */
// 走迷宫帮助类,用以实现迷宫的选路过程和最短路径的优化过程 public class Helper { private int row = 0; private int col = 0;
private char[][] ch1; private char[][] ch2;
private Node current = new Node(); private Node exit = new Node(); private Node entry = new Node();
private static final char EXIT = '@', ENTRY = '#', VISITED = '*';// 出口标记,
入口标记,已经过节点标记 private static final char LOAD = '0', WALL = '1';
// 构造方法:在原地图外围加一圈墙,并设定出口和入口 public Helper(char[][] ch) {
boolean flag = true;
ch1 = new char[ch.length + 2][ch[0].length + 2]; ch2 = new char[ch.length + 2][ch[0].length + 2]; row = ch.length; col = ch[0].length;
for (int i = 0; i < ch.length + 2; i++) {
for (int j = 0; j < ch[0].length + 2; j++) { if (i == 0 || i == ch.length + 1) { }
}
ch1[i][j] = WALL; ch2[i][j] = WALL;
ch1[i][j] = ch[i - 1][j - 1]; ch2[i][j] = ch[i - 1][j - 1]; ch1[i][j] = WALL; ch2[i][j] = WALL;
private Stack
} else if (j != 0 && j != ch[0].length + 1) {
} else {
}
}
for (int i = 0; i < ch.length; i++) { for (int j = 0; j < ch[0].length; j++) { if (ch[i][j] == ENTRY) { }
}
entry.setX(i + 1); entry.setY(j + 1);
ch1[i + 1][j + 1] = ENTRY; ch2[i + 1][j + 1] = ENTRY; flag = false;
} else if (ch[i][j] == EXIT) { exit.setX(i + 1); }
exit.setY(j + 1);
ch1[i + 1][j + 1] = EXIT; ch2[i + 1][j + 1] = EXIT; flag = false;
if (flag) { }
entry.setX(1); entry.setY(1);
ch1[1][1] = ENTRY; ch2[1][1] = ENTRY; exit.setX(col); exit.setY(row); ch1[col][row] = EXIT; ch2[col][row] = EXIT;
// 将未访问的节点压入栈中
private void pushUnvisited(int row, int col) { if (ch1[row][col] == LOAD || ch1[row][col] == EXIT) } // 探路
public void searchTheWay(PrintStream out) {
current = entry; lik.add(current);
while (!current.equals(exit)) {
stk.push(new Node(row, col));
}
}
int row = current.getX(); int col = current.getY(); if (!current.equals(entry)) ch1[row][col] = VISITED; pushUnvisited(row - 1, col); pushUnvisited(row + 1, col); pushUnvisited(row, col - 1); pushUnvisited(row, col + 1); if (stk.empty()) {
out.println(\这是个走不出去的迷宫!\ return; } else { }
current = stk.pop(); lik.add(current);
out.println(\恭喜!成功走出迷宫!\
// 数组输出
private void display(PrintStream out, char[][] ch) { }
for (int i = 1; i <= row; i++) { // out.println(charr[i]); for (int j = 1; j <= col; j++) { out.print(ch[i][j]); }
}
out.println();
// 得到某一条路线
private void getPath() {
if (lik.size() <= 0) return;
Node n = lik.get(lik.size() - 1); while (n != lik.get(0)) {
List
Node target = itr.next(); if (adjoin(n, target)) {
removeElements(lik.indexOf(target) + 1, lik.indexOf(n)); n = target; break;
}
}
}
}
}
// 删除迂回线路
private void removeElements(int from, int to) { }
// 判断两个节点是否相邻
private boolean adjoin(Node current, Node aim) { }
if ((current.getX() == aim.getX() + 1 || current.getX() == aim.getX() - 1) && (current.getY() == aim.getY())) return true; if ((current.getY() == aim.getY() + 1 || current.getY() == aim.getY() - 1)
&& (current.getX() == aim.getX()))
return true; return false;
int turn = to - from; while (turn > 0) { }
lik.remove(from); turn--;
// 输出线路
public void printTheWay(PrintStream out, int a) { }
getPath();
out.println(\
if (lik.size() >= 2) { lik.remove(lik.size() - 1); }
lik.remove(0);
Iterator
Node n = itr.next();
ch2[n.getX()][n.getY()] = VISITED;
display(System.out, (a == 1 ? ch1 : ch2));
Node.java /** * */
package util;
/**
* @author guhonglueying *
*/
public class Node {
public Node(int x, int y) { this.x = x; this.y = y; }
public int getX() { }
return x; private int x; private int y; public Node() { }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { }
public boolean equals(Object o) { if (!(o instanceof Node))
this.y = y;
}
}
return false;
Node n = (Node) o;
return n.x == x && n.y == y;
public String toString() { }
return x + \
TestMaze.java /** *
*/
package test;
import map.*;
import objectmovable.*; /**
* @author guhonglueying * */
public class TestMaze {
/**
* @param args */
// 主函数,程序入口
public static void main(String[] args) { }
//多态实现:三种方式创建迷宫 SubMap sm = new SimpleMap(); sm.create();
char[][] c = sm.getMap(); //多态实现不同物体的走迷宫过程 SubObjectMovable iom = new Ship(); iom.Maze(c);
}
homework07 文件处理 2011-04-08 22:19
1. 读文件, 添加或去掉行号后写回 2. 统计一个文件中的词个数(请注意中文)
AddRowNum.java package sample;
import java.io.*;
public class AddRowNum { // // // // // // // // // //
System.out.println(\System.out.println(\System.out.println(\System.out.println(\System.out.println(\System.out.println(\System.out.println(\System.out.println(\return;
try { /** 开启两个文件, 分别读写 */ BufferedReader reader = new BufferedReader( new FileReader(\
BufferedWriter writer = new BufferedWriter( new FileWriter(\/** 首先取得总行数, 然后逐行添加写回 */ int nRowNum = 0;
String strOneLine = null;
while (reader.readLine() != null) { }
nRowNum++;
public static void main(String[] args) {
reader.close();
String formator = String.format(\nRowNum = 0;
reader = new BufferedReader( new FileReader(\while ((strOneLine = reader.readLine()) != null) {
writer.write(String.format(\ %s\\n\++nRowNum,
strOneLine));
} }
CountWords.java package sample;
import java.io.*;
public class CountWords {
public static void main(String[] args) {
String fileName = \try {
BufferedReader reader = new BufferedReader(new FileReader(fileName)); int NumberCount = 0;
int LetterCount = 0;
int ChineseCharacterCount = 0; int a = -1;
}
(new File(\
writer.close(); reader.close();
new File(\
new File(\
} catch (FileNotFoundException e) { System.out.println(\找不到指定文件\} catch (IOException e) { System.out.println(\文件读写错误\}
Character c;
while ((a = reader.read()) != -1) { c = (char) a; if (Character.isDigit(c)) { NumberCount++;
} else if ('\一' <= c && c <= '\龥') {
ChineseCharacterCount++; } else if (Character.isLetter(c)) { LetterCount++; }
}
reader.close();
System.out.println(\文件\共包含:System.out.println(\数字: \字母: \ + LetterCount + \汉字: \/** 林启敏 */ reader.close();
reader = new BufferedReader(new FileReader(\boolean isWordStart = false;
int count = 0;
char oneChar[] = new char[1];
while (reader.read(oneChar) != -1) { if (oneChar[0] == '.' }
}
|| oneChar[0] == ',' || oneChar[0] == ' ') { if(isWordStart) { }
isWordStart = false; count++;
\
else { }
isWordStart = true;
System.out.println(\
} catch (FileNotFoundException e) { System.out.print(\找不到指定文件\} catch (IOException e) {
}
}
}
System.out.print(\文件读写错误\
homework08 html 2011-04-11 16:24
1. 使用Html实现登录页面, 需提供身份证号码, Email等相关信息 2. 在提交时, 使用JavaScript做校验, 如果失败, 则提示注册者.
login.html
用户注册页面
success.html
注册成功页面
注册成功!
下面自动转入首页......(下次再做吧。)
homework09 Swing 2011-04-17 22:26
1. 使用Swing实现之前Html登录页面, 需提供身份证号码, Email等相关信息 2. 同样在提交时, 程序内部做校验, 失败则提示下相关信息. package homework09;
import java.awt.*;
import java.awt.event.*; import java.util.regex.*; import javax.swing.*; import javax.swing.border.*;
public class LoginWindow {
public static void main(String[] args) { LoginFrame login = new LoginFrame(); login.setTitle(\用户注册界面\ login.setSize(480,360);
login.setLocationRelativeTo(null);
login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); login.setVisible(true); } }
class LoginFrame extends JFrame { public LoginFrame() {
Font defaultFont = new Font(\微软雅黑\
Container loginCon = getContentPane(); LoginPanel panel = new LoginPanel();
TitledBorder inputPanelBorder = new TitledBorder(\基本资料\ inputPanelBorder.setTitleFont(defaultFont);
panel.setBorder(inputPanelBorder); loginCon.add(panel); } }
class LoginPanel extends JPanel {
JTextField nameField,phoneField,emailField,idCardField; JPasswordField passField,repassField; JButton submit,reset;
public LoginPanel() {
BorderLayout layout = new BorderLayout(); setLayout(layout);
nameField = new JTextField(10);
nameField.setMaximumSize(nameField.getPreferredSize());
passField = new JPasswordField(8);
passField.setMaximumSize(passField.getPreferredSize());
repassField = new JPasswordField(8);
repassField.setMaximumSize(repassField.getPreferredSize());
phoneField = new JTextField(12);
phoneField.setMaximumSize(phoneField.getPreferredSize());
emailField = new JTextField(14);
emailField.setMaximumSize(emailField.getPreferredSize());
idCardField = new JTextField(12);
idCardField.setMaximumSize(idCardField.getPreferredSize());
submit = new JButton(\提交\ reset = new JButton(\重置\
Box horizontalBox1 = Box.createHorizontalBox(); Box horizontalBox2 = Box.createHorizontalBox(); Box horizontalBox3 = Box.createHorizontalBox(); Box horizontalBox4 = Box.createHorizontalBox(); Box horizontalBox5 = Box.createHorizontalBox(); Box horizontalBox6 = Box.createHorizontalBox(); Box horizontalBox7 = Box.createHorizontalBox();
horizontalBox1.add(Box.createHorizontalStrut(35)); horizontalBox1.add(new JLabel(\用户名:\
horizontalBox1.add(Box.createHorizontalStrut(12));
horizontalBox1.add(nameField);
horizontalBox1.add(Box.createHorizontalStrut(10)); horizontalBox1.add(new JLabel(\长度为8至16\
horizontalBox2.add(new JLabel(\设置密码:\ horizontalBox2.add(Box.createHorizontalStrut(12)); horizontalBox2.add(passField);
horizontalBox2.add(Box.createHorizontalStrut(10)); horizontalBox2.add(new JLabel(\长度至少为6\
horizontalBox3.add(Box.createHorizontalStrut(30)); horizontalBox3.add(new JLabel(\重复密码:\ horizontalBox3.add(Box.createHorizontalStrut(12)); horizontalBox3.add(repassField);
horizontalBox3.add(Box.createHorizontalStrut(10)); horizontalBox3.add(new JLabel(\两次输入必须一致\
horizontalBox4.add(Box.createHorizontalStrut(60)); horizontalBox4.add(new JLabel(\电话号码:\ horizontalBox4.add(Box.createHorizontalStrut(12)); horizontalBox4.add(phoneField);
horizontalBox4.add(Box.createHorizontalStrut(10)); horizontalBox4.add(new JLabel(\座机或电话号码\
horizontalBox5.add(new JLabel(\邮箱地址:\ horizontalBox5.add(Box.createHorizontalStrut(12)); horizontalBox5.add(emailField);
horizontalBox5.add(Box.createHorizontalStrut(20));
horizontalBox6.add(new JLabel(\身份证信息:\ horizontalBox6.add(Box.createHorizontalStrut(12)); horizontalBox6.add(idCardField);
horizontalBox6.add(Box.createHorizontalStrut(52));
horizontalBox7.add(submit);
horizontalBox7.add(Box.createHorizontalStrut(20)); horizontalBox7.add(reset);
Box verticalBox = Box.createVerticalBox(); verticalBox.add(horizontalBox1);
verticalBox.add(Box.createVerticalStrut(14)); verticalBox.add(horizontalBox2);
verticalBox.add(Box.createVerticalStrut(14)); verticalBox.add(horizontalBox3);
verticalBox.add(Box.createVerticalStrut(14));
verticalBox.add(horizontalBox4);
verticalBox.add(Box.createVerticalStrut(14)); verticalBox.add(horizontalBox5);
verticalBox.add(Box.createVerticalStrut(14)); verticalBox.add(horizontalBox6);
verticalBox.add(Box.createVerticalStrut(18)); verticalBox.add(horizontalBox7);
add(verticalBox);
submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
submit(); } });
reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { }
reset(); } });
void submit() {
String phoneRe = \ String emailRe = \ String idCardRe =
\\
Pattern phonePat = Pattern.compile(phoneRe); Pattern emailPat = Pattern.compile(emailRe); Pattern idCardPat = Pattern.compile(idCardRe);
Matcher phoneMat = phonePat.matcher(phoneField.getText()); Matcher emailMat = emailPat.matcher(emailField.getText()); Matcher idCardMat = idCardPat.matcher(idCardField.getText());
String error = \
if(nameField.getText().equals(\ error = \用户名不能为空!\}
else if(nameField.getText().length()<8 || nameField.getText().length()>16) { error = \用户名长度不符合要求!\}
else if(passField.getText().equals(\ error = \密码不能为空!\}
else if(passField.getText().length()<6) { error = \密码长度不符合要求!\}
else if(!passField.getText().equals(repassField.getText())) { error = \两次输入的密码不一致!\}
else if(phoneField.getText().equals(\ error = \电话号码不能为空!\}
else if(!phoneMat.matches()) { error = \电话号码格式不正确!\}
else if(emailField.getText().equals(\ error = \邮箱地址不能为空!\}
else if(!emailMat.matches()) { error = \邮件地址格式不正确!\}
else if(idCardField.getText().equals(\ error = \身份证信息不能为空!\}
else if(!idCardMat.matches()) { error =\身份证格式不正确!\
}
}
if(error.equals(\ }
else JOptionPane.showMessageDialog(null, error, \消息提示\
JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, \注册成功!\消息提示\ JOptionPane.INFORMATION_MESSAGE); reset();
void reset() { } }
homework10 container 2011-04-24 22:46
1. 使用数组构建栈Stack(FILO)
nameField.setText(null); passField.setText(null); repassField.setText(null); phoneField.setText(null); emailField.setText(null); idCardField.setText(null);
2. 对比Java提供的Stack, 两者有啥区别 3. 使用Stack栈实现\行编辑器\
设立一个输入行冲区, 接受用户逐行的输入, 处理后回显正确的信息
逐行处理过程如下:
有两个特殊字符用来修改该行的错误信息, '#'表示之前一个字符错误, 请删除, '@'表示之前字符全部错误, 请删除前面的全部
示例:
whli##ilr#e(s#*s) -> while(*s)
outcha@putchar(*s=#++); -> putchar(*s++);
MyStack.java package mystack;
/**
* @author 电子商务一班 俞国峰 200930671251 */
public class MyStack {
//currentSize用来记录当前栈中元素个数 private int currentSize; private Object[] Mylist;
//构造函数,创建空栈 public MyStack() {
Mylist = new Object[10]; currentSize = 0;
}
//当数组长度不够时,增加数组长度(每次增加一倍) public void enLargeSize() { }
Object[] tempList = new Object[Mylist.length * 2];
System.arraycopy(Mylist, 0, tempList, 0, Mylist.length); Mylist = tempList;
//判断栈是否为空
public boolean empty() { }
return currentSize == 0;
//入栈
public void push(Object o) { if (currentSize >= Mylist.length) { enLargeSize(); } }
//出栈,返回栈顶元素 public Object pop() { }
//获取栈顶元素
public Object peek() { if (currentSize == 0) { }
}
return null; if (currentSize == 0) { return null; }
currentSize--;
if (currentSize + 1 >= Mylist.length) { enLargeSize(); }
return Mylist[currentSize + 1]; Mylist[currentSize] = new Object(); Mylist[currentSize] = o; currentSize++;
return Mylist[currentSize - 1];
//获取栈大小,返回栈中元素个数 public int getSize() { }
return currentSize;
//清空栈
public void clearAll() { }
//重载toString(),以字符串形式返回栈中元素 @Override
public String toString() {
Mylist = new Object[10]; currentSize = 0;
}
}
String tempString = \
for (int i = 0; i < currentSize; i++) { tempString += Mylist[i].toString(); }
return tempString;
testMyStack.java package mystack;
/**
* @author 电子商务一班 俞国峰 200930671251 */
import java.util.*;
public class testMyStack {
public static void main(String[] args) {
MyStack msk = new MyStack();
Scanner sc = new Scanner(System.in); String input = \
System.out.println(\
\\nYou
may
enter
in:
enter 'exit' or 'EXIT' to exit!\ System.out.println(\example: outcha@putchar(*s=#++);\
System.out.println(\
while (!(input = sc.next()).equalsIgnoreCase(\ char[] charr = input.toCharArray();
System.out.print(\
for (int i = 0; i < charr.length; i++) {
System.out.print(charr[i]); switch (charr[i]) { case '#':
msk.pop(); break;
case '@': msk.clearAll(); break;
}
}
}
}
}
default :
msk.push(charr[i]); break;
System.out.println(\
System.out.print(\
homework11 多线程和网络通信 2011-05-07 21:59
1. 实现UDP模式的客户端和服务器端通信
2. 使用两个线程: 一个线程负责发送消息, 一个线程负责收取并发送消息,两线程间使用LinkedList共享数据
Server.java
package _yu_guo_feng; /*
* @author 电子商务一班 俞国峰 200930671251 *
* 功能:c/s结构,实现基于UDP的聊天功能(包括用户上线提醒,群聊,私聊) * 说明:先开启服务器,再接入客户端(可接入1至多个) * 未完善:服务器多开异常处理,下线提醒 */
import java.awt.*; import javax.swing.*; import java.io.*; import java.net.*;
import java.text.*; import java.util.*;
public class Server extends JFrame {
private static final long serialVersionUID = 3497147855119919874L; private JTextArea jta; //保存当前用户
private LinkedList
private DatagramSocket socket;
private DatagramPacket sendPacket, recevicedPacket; private byte[] buf;
//日期处理
private SimpleDateFormat sdf;
public static void main(String[] args) { }
new Server();
public Server() {
String
introduction
QQ 730
=
寝室版
\ + \欢迎使用 腾讯=================\\n\
+ \+ \使用说明:\\n\+ \运行服务器\\n\+ \接入客户端(可接入多个)\\n\
+ \功能:上线提醒、群聊和私聊\\n\ + \作者:电子商务一班——俞国峰——200930671251========\\n\ + \
try {
socket = new DatagramSocket(8888); } catch (SocketException e) { e.printStackTrace();
jta = new JTextArea(introduction);
this.setIconImage((new ImageIcon(\this.setTitle(\腾讯QQ 730寝室版——服务器\this.add(jta, BorderLayout.CENTER); this.setSize(400, 300); this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true);
sclient = new LinkedList
sdf = new SimpleDateFormat(\
}
}
//接受并转发给各客户端 dealInfo();
public void dealInfo() {
while (true) {
buf = new byte[256];
sendPacket = new DatagramPacket(buf, buf.length);
recevicedPacket = new DatagramPacket(buf, buf.length); try {
socket.receive(recevicedPacket);
//两个判断分别是:1,登录处理:接受登录提醒,并转发给当前所有用户;
2,聊天数据报转发
if ((new String(buf)).trim().charAt(0) == '@') {
jta.append(\用户 【\】 上线了...\ SClient current = new SClient(recevicedPacket.getAddress(), recevicedPacket.getPort(),(new String(buf)).split(\
sclient.add(current);
for (int i = 0; i < sclient.size(); i++) {
(\
+
//将新上线用户告知其他用户 sendMessage(sclient.get(i), current.getName().trim()).getBytes());
//将当前在线用户告知新上线用户 sendMessage(current,
(\+
sclient.get(i).getName().trim()).getBytes()); }
} else {
String[]
tempStringArray
=
(new
String(buf)).trim().split(\ String current = tempStringArray[0];
String client = tempStringArray[1];
//群聊处理:1,当前没有其他用户,回复该用户; 2,当前有其他用户,if (client.equals(\所有人\
if (sclient.size() == 1) {
将该数据报群发
sendMessage(recevicedPacket.getAddress(),
recevicedPacket.getPort(), \当前没有其他用户同时在线\ } else { for (int i = 0; i < sclient.size(); i++) { sendMessage(sclient.get(i), buf);
}
//用登录名获取该用户
public SClient selectByName(String name) { }
for (int i = 0; i < sclient.size(); i++) { if (sclient.get(i).getName().trim().equals(name)) { }
}
return sclient.get(i);
}
}
}
}
//私聊处理 } else { }
sendMessage(selectByName(current), buf); sendMessage(selectByName(client), buf);
} catch (IOException e) { }
e.printStackTrace();
return null;
//服务器转发数据报:通过参数SClient
public void sendMessage(SClient sc, byte[] bf) { this.sendMessage(sc.getAddress(), sc.getPort(), bf); }
//方法重载,服务器转发数据报,通过参数ip和port
public void sendMessage(InetAddress address, int port, byte[] buf) {
try {
sendPacket.setData(buf);
sendPacket.setAddress(address); sendPacket.setPort(port);
}
socket.send(sendPacket);
} catch (IOException e) { e.printStackTrace(); }
//内部类,SClient类,拥有Client对象的信息,包括:登录名, ip, port private class SClient {
private String name;
private InetAddress address; private int port; public SClient() { }
public SClient(InetAddress address, int port, String name) { this.address = address; }
public String getName() { return name; }
public InetAddress getAddress() { return address; }
public int getPort() { }
return port; this.port = port; this.name = name;
public void setName(String name) { }
public void setAddress(InetAddress address) { }
public void setPort(int port) {
this.address = address; this.name = name;
}
}
}
this.port = port;
Client.java
package _yu_guo_feng; /*
* @author 电子商务一班 俞国峰 200930671251 *
* 功能:c/s结构,实现基于UDP的聊天功能(包括用户上线提醒,群聊,私聊) * 说明:先开启服务器,再接入客户端(可接入1至多个) * 未完善:服务器多开异常处理,下线提醒 */
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; import java.text.*;
public class Client extends JFrame implements Runnable {
private static final long serialVersionUID = -5865959502132974616L; //登录名
private static String name; private JTextArea jta; private JScrollPane jsp; private JComboBox jcb; private JTextField jtf; private JButton jb; private JPanel jp;
private DatagramSocket socket; private InetAddress address;
private DatagramPacket sendPacket, recevicedPacket; private byte[] buf; //日期处理
private SimpleDateFormat sdf;
public static void main(String[] args) {
name = JOptionPane.showInputDialog(null, \请输入您的登录名:\\请登录...\JOptionPane.QUESTION_MESSAGE);
//对\发送\按钮进行监听注册,按下按钮,发送内容 jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SendMessage(name + \+ jcb.getSelectedItem().toString() + \+ jtf.getText().trim());
});
//对输入框进行监听注册,按下回车,发送内容 jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { SendMessage(name + \ }
jtf.setText(\
jta = new JTextArea();
jsp = new JScrollPane(jta);
String[] s = new String[]{\所有人\jcb = new JComboBox(s); jtf = new JTextField(20); jb = new JButton(\发送\
jta.setEditable(false);
jb.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }
public Client() {
new Client();
\ jtf.setText(\
jp = new JPanel();
jp.setLayout(new BorderLayout()); jp.add(jcb, BorderLayout.WEST); jp.add(jtf, BorderLayout.CENTER); jp.add(jb, BorderLayout.EAST);
this.setIconImage((new ImageIcon(\
} });
}
this.setTitle(\腾讯QQ 730寝室版 【\】聊天中...\this.add(jsp, BorderLayout.CENTER); this.add(jp, BorderLayout.SOUTH); this.setSize(400, 300); this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); try {
socket = new DatagramSocket();
//获得本机ip地址 address = InetAddress.getByName(\} catch (SocketException e) {
System.out.println(\客户端连接失败,请重新连接\} catch (UnknownHostException e) { }
System.out.print(\地址获取失败,请重启客户端\
buf = new byte[256];
sendPacket = new DatagramPacket(buf, buf.length, address, 8888); //登录,并通知服务器进行注册
jta.append(\恭喜!用户 【\】 登录成功!\\n\SendMessage(\
//指定时间表示模式
sdf = new SimpleDateFormat(\
//启动一个新线程,用来接受显示来自服务器的数据报 Thread thread = new Thread(this); thread.start();
//发送信息数据报给服务器
public void SendMessage(String str) { }
try { }
sendPacket.setData(str.getBytes()); socket.send(sendPacket); e.printStackTrace();
} catch (IOException e) {
//此方法参考sun公司 api 1.6版,用以防止JComboBox中item重复 private Object makeObj(final String item) { return new Object() { public String toString() { return item; }
//重写run方法,用来接受来自服务器的数据报 public void run() {
while (true) {
try { buf = new byte[256];
recevicedPacket = new DatagramPacket(buf, buf.length); socket.receive(recevicedPacket); } catch (IOException e) { }
//三个判断分别是:1,其他用户上线提醒; 2,没有其他用户时提醒; 3,聊天互String tempReceivedPacket = new String(buf);
if (new String(buf).charAt(0) == '@') { String n = tempReceivedPacket.split(\
if (!n.equals(name)) { e.printStackTrace();
};
}
动
jta.append(\上线了...\\n\ //将新上线的用户加入JComboBox
jcb.addItem(makeObj(tempReceivedPacket.split(\
}
} else if (new String(buf).charAt(0) == '#') {
jta.append(\+ tempReceivedPacket.split(\+
\
} else {
String[] tempStringArray = tempReceivedPacket.split(\String tempName = tempStringArray[0].trim(); String tempMessage = tempStringArray[2].trim();
jta.append(\
+ \ }
}
}
}
homework12 数据库操作(呃,好像没人做的样子哈,求答案) 2011-05-16 01:35
作业homework11是使用UDP通信方式在客户端和服务器端通信, 此处修改为使用数据库模式在客户端和服务器端通信.
正在阅读:
寿辰答谢词12-31
干群编织“安全网”,为学生保驾护航 - 谈宋桂镇成立校外安全协委会的做法及成效(江伟容)03-13
GIS二次开发实验指导书(实验5)05-16
噶米地基承载力特征值、地基承载力设计值、地基承载力标准12-02
区街道办事处2021年特色亮点工作及2022年工作规划08-02
搪瓷反应釜维护保养标准操作规程09-11
(戴洪)我的再发展行动计划06-12
美是什么作文400字06-16
2022年建筑《安全员》考试题库04-20
- 多层物业服务方案
- (审判实务)习惯法与少数民族地区民间纠纷解决问题(孙 潋)
- 人教版新课标六年级下册语文全册教案
- 词语打卡
- photoshop实习报告
- 钢结构设计原理综合测试2
- 2014年期末练习题
- 高中数学中的逆向思维解题方法探讨
- 名师原创 全国通用2014-2015学年高二寒假作业 政治(一)Word版
- 北航《建筑结构检测鉴定与加固》在线作业三
- XX县卫生监督所工程建设项目可行性研究报告
- 小学四年级观察作文经典评语
- 浅谈110KV变电站电气一次设计-程泉焱(1)
- 安全员考试题库
- 国家电网公司变电运维管理规定(试行)
- 义务教育课程标准稿征求意见提纲
- 教学秘书面试技巧
- 钢结构工程施工组织设计
- 水利工程概论论文
- 09届九年级数学第四次模拟试卷
- 华南理工大学
- 程序设计
- 课堂
- 作业
- 答案
- 语言
- Java