代码如下:
import java.util.Scanner;
public class Perceptron {
private static int N = 3;
private static int n = 2;
private static double[][] X = null;
private static double[] Y = null;
private static double[][] G = null;
private static double[] A = null;
private static double[] W = null;
private static double B = 0;
private static double fi = 0.5;
private static boolean check(int id) {
double ans = B;
for(int i=0;i<N;i++)
ans += A[i] * Y[i] * G[i][id];
if(ans * Y[id] > 0) return true;
return false;
}
public static void solve() {
Scanner in = new Scanner(System.in);
System.out.print("input N:"); N = in.nextInt();
System.out.print("input n:"); n = in.nextInt();
X = new double[N][n];
Y = new double[N];
G = new double[N][N];
System.out.println("input N * n datas X[i][j]:");
for(int i=0;i<N;i++)
for(int j=0;j<n;j++)
X[i][j] = in.nextDouble();
System.out.println("input N datas Y[i]");
for(int i=0;i<N;i++)
Y[i] = in.nextDouble();
for(int i=0;i<N;i++)
for(int j=0;j<N;j++) {
G[i][j] = 0;
for(int k=0;k<n;k++)
G[i][j] += X[i][k] * X[j][k];
}
A = new double[N];
W = new double[n];
for(int i=0;i<n;i++) A[i] = 0;
B = 0;
boolean ok = true;
while(ok == true) {
ok = false;
//这里在原来算法的基础上不断地将fi缩小,以避免跳来跳去一直达不到要求的点的效果。
for(int i=0;i<N;i++) {
//System.out.println("here " + i);
while(check(i) == false) {
ok = true;
A[i] += fi;
B += fi * Y[i];
//debug();
}
}
fi *= 0.5;
}
for(int i=0;i<n;i++)
W[i] = 0;
for(int i=0;i<N;i++)
for(int j=0;j<n;j++)
W[j] += A[i] * Y[i] * X[i][j];
}
public static void main(String[] args) {
solve();
System.out.print("W = [");
for(int i=0;i<n-1;i++) System.out.print(W[i] + ", ");
System.out.println(W[n-1] + "]");
System.out.println("B = " + B);
}
}
posted @
2015-03-20 11:34 marchalex 阅读(856) |
评论 (0) |
编辑 收藏
实现时遇到一个问题,就是fi的值的设定问题,因为我们采用随机梯度下降法,一方面这节省了时间,但是如果fi值亘古不变的话可能会面临跳来跳去一直找不到答案的问题,所以我这里设定他得知在每一轮之后都会按比例减小(fi *= 0.5;),大家可以按自己的喜好自由设定。
import java.util.Scanner;
public class Perceptron {
private static int N = 3;
private static int n = 2;
private static double[][] X = null;
private static double[] Y = null;
private static double[] W = null;
private static double B = 0;
private static double fi = 0.5;
private static boolean check(int id) {
double ans = B;
for(int i=0;i<n;i++)
ans += X[id][i] * W[i];
if(ans * Y[id] > 0) return true;
return false;
}
private static void debug() {
System.out.print("debug: W");
for(int i=0;i<n;i++) System.out.print(W[i] + " ");
System.out.println("/ B : " + B);
}
public static void solve() {
Scanner in = new Scanner(System.in);
System.out.print("input N:"); N = in.nextInt();
System.out.print("input n:"); n = in.nextInt();
X = new double[N][n];
Y = new double[N];
W = new double[n];
System.out.println("input N * n datas X[i][j]:");
for(int i=0;i<N;i++)
for(int j=0;j<n;j++)
X[i][j] = in.nextDouble();
System.out.println("input N datas Y[i]");
for(int i=0;i<N;i++)
Y[i] = in.nextDouble();
for(int i=0;i<n;i++) W[i] = 0;
B = 0;
boolean ok = true;
while(ok == true) {
ok = false;
//这里在原来算法的基础上不断地将fi缩小,以避免跳来跳去一直达不到要求的点的效果。
for(int i=0;i<N;i++) {
//System.out.println("here " + i);
while(check(i) == false) {
ok = true;
for(int j=0;j<n;j++)
W[j] += fi * Y[i] * X[i][j];
B += fi * Y[i];
//debug();
}
}
fi *= 0.5;
}
}
public static void main(String[] args) {
solve();
System.out.print("W = [");
for(int i=0;i<n-1;i++) System.out.print(W[i] + ", ");
System.out.println(W[n-1] + "]");
System.out.println("B = " + B);
}
}
posted @
2015-03-20 11:08 marchalex 阅读(629) |
评论 (0) |
编辑 收藏
这个应用主要是为了生成座位的安排。程序运行后,在菜单栏中选择打开文件,然后我们假设文件的格式为:每一行一个人名。
例:
风清扬
无名僧
东方不败
任我行
乔峰
虚竹
段誉
杨过
郭靖
黄蓉
周伯通
小龙女
这个程序的特点如下:
在JFrame中添加了菜单栏;
在画布中添加了诸多元素;
最后会将图片通过图片缓存保存到本地“frame.png”中。
代码如下:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class FrameWork extends JFrame {
private static final double pi = Math.acos(-1.0);
private static final int Width = 1000;
private static final int Height = 600;
private static JFrame frame = null;
private static int personNumber = 15;
private static String[] names = new String[100];
public FrameWork() {
frame = new JFrame("Java菜单栏");
//JList list = new JList();
//frame.add(list);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("文件");
JMenu openMenu = new JMenu("打开");
JMenuItem openItem = new JMenuItem("文件");
openMenu.add(openItem);
openItem.addActionListener(new MyAction());
fileMenu.add(openMenu);
menuBar.add(fileMenu);
frame.setLocationRelativeTo(null);
frame.setSize(Width, Height);
frame.setLocation(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel panel = new ImagePanel();
//panel.setBounds(0, 0, Width, Height);
//frame.getContentPane().add(panel);
frame.setVisible(true);
}
private static int getNumber1(int i) {
int n = personNumber;
if((n-1)/2*2-2*i >= 0) return (n-1)/2*2 - 2*i;
return (i-(n-1)/2)*2-1;
}
private static int getNumber2(int i) {
if(i*2+1 <= personNumber) return i*2;
return 2*(personNumber-i)-1;
}
private class MyAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
//Object s = evt.getSource();
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
jfc.showDialog(new JLabel(), "选择");
File file=jfc.getSelectedFile();
/*if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件:"+file.getAbsolutePath());
}*/
personNumber = 0;
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
while((names[personNumber]=reader.readLine()) != null) {
personNumber ++;
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new ImagePanel();
panel.setBounds(0, 0, Width, Height);
frame.getContentPane().add(panel);
frame.setVisible(true);
//System.out.println(personNumber);
//for(int i=0;i<personNumber;i++)
//System.out.println(names[i]);
BufferedImage bi = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
frame.paint(g2d);
try {
ImageIO.write(bi, "PNG", new File("D:\\frame.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ImagePanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.white);
g.fillRect(0, 0, Width, Height);
g.setColor(Color.black);
int delx = (Width - 20) / (personNumber + 1);
for(int i=0;i<personNumber;i++) {
int x = i * delx + 10;
g.drawRect(x, 10, delx, 20);
//String s = "" + getNumber1(i);
int id = getNumber1(i);
String s = names[id];
g.drawString(s, x+2, 22);
//s = "" + getNumber2(i);
id = getNumber2(i);
s = names[id];
int x0 = 440, y0 = 285, r = 170;
int xx = (int) (x0 - r * Math.sin(pi*2*i/personNumber));
int yy = (int) (y0 - r * Math.cos(pi*2*i/personNumber));
g.drawString(s, xx, yy);
}
g.drawOval(300, 130, 300, 300);
}
}
public static void main(String[] args) {
new FrameWork();
}
}
posted @
2015-03-18 20:20 marchalex 阅读(282) |
评论 (0) |
编辑 收藏
写了一个FrameWork类实现了菜单栏,并且为菜单栏里的Item添加事件监听,实现了选择文件的功能。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class FrameWork extends JFrame {
private static final int Width = 1000;
private static final int Height = 600;
private static JFrame frame = null;
private static FlowLayout flowLayout = null;
public FrameWork() {
frame = new JFrame("Java菜单栏");
flowLayout = new FlowLayout(FlowLayout.CENTER);
flowLayout.setHgap(20);
flowLayout.setVgap(30);
frame.setLayout(flowLayout);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("文件");
JMenu openMenu = new JMenu("打开");
JMenuItem openItem = new JMenuItem("文件");
openMenu.add(openItem);
openItem.addActionListener(new MyAction());
fileMenu.add(openMenu);
menuBar.add(fileMenu);
frame.setVisible(true);
frame.setSize(Width, Height);
frame.setLocation(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MyAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Object s = evt.getSource();
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
jfc.showDialog(new JLabel(), "选择");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件:"+file.getAbsolutePath());
}
System.out.println(jfc.getSelectedFile().getName());
}
}
public static void main(String[] args) {
new FrameWork();
}
}
posted @
2015-03-18 12:51 marchalex 阅读(936) |
评论 (0) |
编辑 收藏
setFileSelectionMode(int mode)
设置 JFileChooser
,以允许用户只选择文件、只选择目录,或者可选择文件和目录。
mode参数:FILES_AND_DIRECTORIES
指示显示文件和目录。
FILES_ONLY
指示仅显示文件。
DIRECTORIES_ONLY
指示仅显示目录。
showDialog(Component parent,String approveButtonText)
弹出具有自定义 approve 按钮的自定义文件选择器对话框。
showOpenDialog(Component parent)
弹出一个 "Open File" 文件选择器对话框。
showSaveDialog(Component parent)
弹出一个 "Save File" 文件选择器对话框。
setMultiSelectionEnabled(boolean b)
设置文件选择器,以允许选择多个文件。
getSelectedFiles()
如果将文件选择器设置为允许选择多个文件,则返回选中文件的列表(File[])。
getSelectedFile()
返回选中的文件。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileChooser extends JFrame implements ActionListener{
JButton open=null;
public static void main(String[] args) {
new FileChooser();
}
public FileChooser(){
open=new JButton("open");
this.add(open);
this.setBounds(400, 200, 100, 100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
open.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
jfc.showDialog(new JLabel(), "选择");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件:"+file.getAbsolutePath());
}
System.out.println(jfc.getSelectedFile().getName());
}
}
posted @
2015-03-18 12:35 marchalex 阅读(553) |
评论 (0) |
编辑 收藏
今天写了一个在JFrame显示图片(包括动图)的小程序。
主要用到了
JPanel类,JPanel类有一个paint()方法,用于实现画图。在这里paint()方法里写的就是调用一张图片,然后就实现了在JFrame中显示一张图片。
其原理其实是:在JFrame对象中放一个JPanel对象,在JPanel中实现画图。
代码如下:
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageApp extends JFrame {
public ImageApp() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 300);
setResizable(false);
getContentPane().setLayout(null);
JPanel panel = new ImagePanel();
panel.setBounds(0, 0, 400, 300);
getContentPane().add(panel);
setVisible(true);
}
public static void main(String[] args) {
new ImageApp();
}
class ImagePanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
ImageIcon icon = new ImageIcon("D:\\testapp.jpg");
g.drawImage(icon.getImage(), 0, 0, 400, 300, this);
}
}
}
动图如下:(D:\\testapp.jpg)
posted @
2015-03-13 11:32 marchalex 阅读(3294) |
评论 (0) |
编辑 收藏
在之前写过一个
TranslateHelper类用于在线翻译英文单词。
我之前写过一个
单词翻译大师用于将文件中出现的所有单词存储在另一个文件中。存储的格式如下:
word: explain
如:
apple: 苹果;苹果树;苹果公司
banana: 香蕉;芭蕉属植物;喜剧演员
我们假设这里获取单词的原文件为D:|test_english.txt
存储单词的文件为D:\word_lib.txt
这次写的TranslateHelper2类就是在此基础上编写的一个英汉词典的离线版本。
在此之前我写了一个WordFinder类用于获取D:\word_lib.txt下的特定单词及其解释(没有的话返回null)。
WordFinder.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class WordFinder {
public static String find(String word) throws Exception {
String filename = new String("D:\\word_lib.txt");
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = "";
while((line = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ":");
String key = st.nextToken();
if(key.equals(word)) {
return st.nextToken();
}
}
return null;
}
public static void main(String[] args) throws Exception {
String ans = find("apple");
System.out.println(ans);
}
}
下面是TranslateHelper2类,其词库是基于文件D:\word_lib.txt的,如下:
新增了一个按键可在线更新词库,即D:\word_lib.txt里面的内容(在现实点按键可更新)。
TranslateHelper2.java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TranslateHelper2 extends JFrame {
private static final int Width = 500;
private static final int Height = 220;
private static JFrame frame = null;
private static FlowLayout flowLayout = null;
private static JLabel label = null;
private static JTextField wordText = null;
private static JTextField explainText = null;
private static JButton button = null;
private static JButton new_button = null;
public TranslateHelper2() {
frame = new JFrame("Translate Helper");
flowLayout = new FlowLayout(FlowLayout.CENTER);
flowLayout.setHgap(20);
flowLayout.setVgap(30);
frame.setLayout(flowLayout);
label = new JLabel("单词:");
wordText = new JTextField(10);
explainText = new JTextField(40);
button = new JButton("提交");
new_button = new JButton("在线时点击可更新");
frame.add(label);
frame.add(wordText);
frame.add(button);
frame.add(explainText);
frame.add(new_button);
button.addActionListener(new ButtonAction());
new_button.addActionListener(new ButtonAction());
frame.setVisible(true);
frame.setSize(Width, Height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Object s = evt.getSource();
//System.out.println("hello");
if(s == button) {
String word = wordText.getText();
try {
String _word = word;
String _explain = WordFinder.find(word);
wordText.setText(_word);
explainText.setText(_explain);
} catch (Exception e) {
e.printStackTrace();
}
} else if(s == new_button) {
try {
TranslateMaster.translateAllLocal("D:\\test_english.txt", "D:\\word_lib.txt");
} catch (Exception e) {
return;
}
}
}
}
public static void main(String[] args) {
new TranslateHelper2();
}
}
posted @
2015-03-11 13:25 marchalex 阅读(404) |
评论 (0) |
编辑 收藏
之前写过
FileHelper类,其中的readFile和writeFile方法分别用于文件的读和写。这次在原来的基础上添加了如下方法:
- listFiles
- hasWords
- findFilesContainsWords
- 递归地查找某一目录下所有包含某一关键字的所有文件(这里我加了一个过滤器,即我只找了所有后缀为“.h”的文件)。
加了新功能后的FileHelper类代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FileHelper {
public static String readFile(String filename) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String ans = "", line = null;
while((line = reader.readLine()) != null){
ans += line + "\r\n";
}
reader.close();
return ans;
}
public static void writeFile(String content, String filename) throws Exception {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(content);
writer.flush();
writer.close();
}
public static void listFiles(String path) {
File file = new File(path);
File[] files = file.listFiles();
if(files == null)
return;
for(File f : files) {
if(f.isFile()) {
System.out.println(f.toString());
} else if(f.isDirectory()) {
System.out.println(f.toString());
listFiles(f.toString());
}
}
}
public static boolean hasWords(String file, String words) {
try {
String s = readFile(file);
int w_len = words.length();
int len = s.length();
for(int i=0;i+w_len<=len;i++) {
if(s.substring(i, i+w_len).equals(words))
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void findFilesContainsWords(String path, String words) throws Exception {
File file = new File(path);
File[] files = file.listFiles();
if(files == null) return;
for(File f : files) {
if(f.isFile()) {
String s = f.toString();
int s_len = s.length();
if(s.substring(s_len-2, s_len).equals(".h") == false) continue; // add filter
if(hasWords(f.toString(), words))
System.out.println(f.toString());
} else if(f.isDirectory()) {
findFilesContainsWords(f.toString(), words);
}
}
}
public static void main(String[] args) throws Exception {
//String ans = readFile("D:\\input.txt");
//System.out.println(ans);
//writeFile(ans, "D:\\output.txt");
//findFilesContainsWords("D:\\clamav-0.98.6", "scanmanager");//在IDE中找
if(args.length != 1) {
System.out.println("Usage : \"D:\\clamav-0.98.6\" words");
return;
}
findFilesContainsWords("D:\\clamav-0.98.6", args[0]);//在命令行中找
}
}
posted @
2015-03-10 16:11 marchalex 阅读(580) |
评论 (0) |
编辑 收藏
这是我很多月以前学习
马士兵的Java教学视频的时候在教程的基础上稍微改进了一点的一个聊天室软件。
聊天室软件分为ChatClient类和ChatServer类。
ChatServer相当于一个服务器。
ChatClient类相当于一个客户端。
用户可以通过客户端进行聊天。
客户端登录时会询问你的姓名,输入姓名后大家就可以基于此聊天室软件进行聊天了。
CHatClient.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
private String name;
//private boolean named = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
setVisible(true);
connect();
tfTxt.addActionListener(new TFListener());
//new Thread(new RecvThread()).start();
tRecv.start();
}
public void connect() {
try {
socket = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
System.out.println("connected!");
taContent.setText("你叫什么名字?\n");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
bConnected = false;
tRecv.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
private class TFListener implements ActionListener {
private boolean named = false;
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
if(named == false) {
named = true;
name = str;
try {
dos.writeUTF(name+" is coming!");
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
try {
//dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(name + ":" + str);
dos.flush(); //dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
private String name;
public void run() {
/*
while(bConnected) {
try {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText()+str+'\n');
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("退出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
*/
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText()+str+'\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("退出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started =
false;
ServerSocket ss =
null;
List<Client> clients =
new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss =
new ServerSocket(8888);
started =
true;
}
catch (BindException e) {
System.out.println("端口使用中
");
System.out.println("请关掉相应程序并重新运行服务器!");
System.exit(0);
}
catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c =
new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
ss.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Client
implements Runnable {
private Socket s;
private DataInputStream dis =
null;
private DataOutputStream dos =
null;
private boolean bConnected =
false;
public Client(Socket s) {
this.s = s;
try {
dis =
new DataInputStream(s.getInputStream());
dos =
new DataOutputStream(s.getOutputStream());
bConnected =
true;
}
catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
}
catch (IOException e) {
clients.remove(
this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(
int i=0;i<clients.size();i++) {
Client c = clients.get(i);
c.send(str);
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
}
catch (EOFException e) {
System.out.println("Client closed!");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(dis !=
null) dis.close();
if(dos !=
null) dos.close();
if(s !=
null) {
s.close();
s =
null;
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
posted @
2015-03-09 08:39 marchalex 阅读(574) |
评论 (0) |
编辑 收藏
上次写了一个基于iciba的
英汉翻译,这次在原来的基础上加了一个窗口,实现了TranslateHelper类。
效果如下:
代码如下:
import java.awt.FlowLayout;
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;
public class TranslateHelper extends JFrame {
private static final int Width = 500;
private static final int Height = 200;
private static JFrame frame = null;
private static FlowLayout flowLayout = null;
private static JLabel label = null;
private static JTextField wordText = null;
private static JTextField explainText = null;
private static JButton button = null;
public TranslateHelper() {
frame = new JFrame("Translate Helper");
flowLayout = new FlowLayout(FlowLayout.CENTER);
flowLayout.setHgap(20);
flowLayout.setVgap(30);
frame.setLayout(flowLayout);
label = new JLabel("单词:");
wordText = new JTextField(10);
explainText = new JTextField(40);
button = new JButton("提交");
frame.add(label);
frame.add(wordText);
frame.add(button);
frame.add(explainText);
button.addActionListener(new ButtonAction());
frame.setVisible(true);
frame.setSize(Width, Height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ButtonAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
//Object s = evt.getSource();
//System.out.println("hello");
String word = wordText.getText();
try {
String _word = EnglishChineseTranslater.getWordName(word);
String _explain = EnglishChineseTranslater.getTranslation(word);
wordText.setText(_word);
explainText.setText(_explain);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new TranslateHelper();
}
}
posted @
2015-03-08 18:47 marchalex 阅读(202) |
评论 (0) |
编辑 收藏