Monday, 7 May 2007
文字输入组件的使用与介绍
9-1:认识Swing的文字输入组件:
Swing与文字输入有关的组件分别是JTextField、JPasswordField、JTextArea、JEditorPane与JTextPane.JTextField与
JPasswordField为单行的文本编辑器;JTextArea为多行的文本编辑器;JEditorPane可显示多种文件格式;JTextPane可设置文件各种
样式。这些组件都继承了JTextComponent为类,它们之间的关系如下:
|--JTextField--JPasswordField
|
JTextComponent|
|--JTextArea
|
|--JEditorPane--JTextPane
JTextComponent提供了相当多实用的方法,可使处理输入组件更为方便,例如copy(),paste(),cut(),getText(),setText()等
相当直觉的方法:另外还有设置是否可编辑(setEditable()),setSelectionEnd(),setSelectionStart())、设置或取得光标位置
(getCaretPosition(),setCaretPosition())等等,这些相当常用的方法你都可以在JTextComponent类中找到.
Swing的文字输入组件均以Document来当作数据模式,当输入组件的内容有所改变时,均是更改此Document的内容。因此你可
以将同一个Document内容以不同的输入组件来显示,这就是MVC概念的一个基本应用。Document为一个interface,你可以实现此界
面或利用java提供的默认类来构造文字输入组件。
|---implements-->AbstractDocument---extends->PlainDocument
|
Document |
|
|--extends-->StyleDocument---implements--->DefaultStyleDocument---extends--->HTMLDocument
AbstractDocument----extends-->DefaultStyleDocument
PlainDocument是一个实体类,已经实现了AbstractDocument与Document中的所有抽象方法,你可以用此类直接构造出JTextField
、JPasswordField与JTextArea组件;相同的,你可以使用DefaultStyledDocument构造出JTextPane组件,这些关系我们均会在下面
各节中提到。下面我们开始介绍各种文字输入组件的使用:
9-2:使用JTextField组件:
JTextField继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如copy(),paste(),setText()
,isEditable()等等。我们可以在很多地方使用JTextField,JTextField是一个单行的输入组件,那么有没有多行的输入组件呢?有
的,就是JTextArea,我们将在后面介绍.
JTextField构造函数:
JTextField()
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始化字符串和
字段长度。
JTextField(int columns):建立一个新的JTextField并设置其初始字段长度。
JTextField(String text):建立一个新的JTextField并设置其初始字字符串。
JTextField(String text,int columns):建立一个新的JTextField并设置其初始字符串和字段长度.
9-2-1:构造一般的JTextField组件:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField1{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField();
JTextField t2 = new JTextField(2);
JTextField t3 = new JTextField("175cm");
JTextField t4 = new JTextField("50kg太瘦了",10);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-2-2:利用Document构造JTextField:
Document是一个interface,主要的功能是定义一些方法,让我们在使用所有与Text相关的组件时,能够将输入文字的内容加以
结构化或规格化。将文字内容结构化又是什么呢?举例来说,就好像一本书的内容,它的结构一定会有各个大章,在各章中又会分
成许多小节,小节内会再有各个小重点等等,这样的树状组件结构就是结构化的一种。由于这个interface定义了10几个方法,但是
在这里我们所会用到的只有少数几个方法,为了不让大家混淆,因此我们先列出这个interface常被使用到的方法,有兴趣的可查阅
java api文件:
void addDocumentListener(DocumentListener listener):增加DocumentListener,使组件具有处理DocumentEvent功能。
void addUndoableEditListener(UndoableEditListener listener):增加UndoableEditListener,使组件具有处理UndoableEditEv
Ent功能,当文件中的内容被修改时自动记忆可以被复原的内容。
String getText(int offset,int length):取得document中的文字内容。
void insertString(int offset,String str,AttributeSet a):将字符串加入到Text组件的内容中。
void removeDocumentListener(DocumentListener listener):移除DocumentListener.
void removeUndoableEditListener(UndoableEditListener listener):移除UndoableEditListener,使复原功能失效。
还记得我们一开始在介绍JTextField时所提到的构造函数吗?其中有一个JTextField的构造函数是这样子的:
JTextField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JTextField并设置其初始
化字符串和字段长度。
因此我们必须实作Document所有的方法,才能利用Document构造出JTextField,这样的做法有点麻烦,因为我们之前有提到Document
的方法有数十种,但是我们要用到的却只有其中几种,若是要将全部的方法实作那是相当费时的做法。大家还记行我们前几章介绍
JList时,利用继承AbstractListModel的抽象类来构造JList吗?由于抽象类已经了许多接口的方法,所以当我们继承这个抽象类后
便不需要实作这些方法。同样的java在这里也提供了一个AbstractDocument的抽象类来供我们使用。不过在这里我们并不是要使用
AbstractDocument,因为java在这部份已经提供了一个实体类:PlainDocument.这个实体类继承AbstractDocument,也就是具备了所
有AbstractDocument的方法,所以我们只要直接继承PlainDocument这个实体类就能利用Document来构造JTextField.这种概念跟
JList或是JTable的模式结构均是相同的。我们来看下面的范例:
JTextField3.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField3{
public static void main(String args[]) {
JFrame f = new JFrame("JTextField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JTextField t1 = new JTextField(new JTextField3_FixedLengthDocument(10),"",10);
JTextField t2 = new JTextField(new JTextField3_FixedLengthDocument(1),"",2);
JTextField t3 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
JTextField t4 = new JTextField(new JTextField3_FixedLengthDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
JTextField3_FixedLengthDocument.java
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JTextField3_FixedLengthDocument extends PlainDocument{
private int maxLength;
public JTextField3_FixedLengthDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
9-2-3:JTextField的事件处理:
在JTextField类中有addActionListener()方法,可以检测到用户是否在JTextField上按下Enter键,就如同前面所介绍JButton按
下按钮时所产生的事件(Event)一样,我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextField4{
public static void main(String[] args){
JFrame f=new JFrame("JTextField4");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(2,2));
p1.setBorder(BorderFactory.createTitledBorder("JTextField事件处理范例"));
JLabel l1=new JLabel("输入");
JLabel l2=new JLabel("输入后,按下Enter==>");
final JLabel l3=new JLabel("");
final JTextField t1=new JTextField();
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
l3.setText(t1.getText());
}
});
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(l3);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3:使用JPasswordField组件:
JPasswordField的类层次结构图:
java.lang.Object
--java.awt.Component
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JTextField
--javax.swing.JPasswordField
一般我们在网络中填写登录密码时,密码都会显示"*"号代表用户输入的字段,这样可避免用户输入的密码信息被旁人所偷窥。
而Swing中的JPasswordField就可以提供这样的功能。JPasswordField继承JTextField类,因此它也可以使用JTextField类里面许多
好用的方法,如addActionListener()、removeActionListener()、setHorizontalAlignment()等等。如同JTextField一样
JPasswordField也是一个单行的输入组件,不同的是JPasswordField多了屏蔽(Mask)的功能,也就是说在JPasswordField中的字符
都会以单一种的字符类型表现出来。
在使用JPasswordField之前,我们先看看它的构造函数:
JPasswordField()
JPasswordField(Document doc,String text,int columns):使用指定的文件存储模式建立一个新的JPasswordField并设置其初始化
字符串和字段长度。
JPasswordField(int columns):建立一个新的JPasswordField并设置其初始字段长度。
JPasswordField(String text):建立一个新的JPasswordField并设置其初始字字符串。
JPasswordField(String text,int columns):建立一个新的JPasswordField并设置其初始字符串和字段长度.
9-3-1:构造一般的JPasswordField组件:
JPasswordField的构造函数和JTextField的构造函数几乎一模本样,唯一不同的是在JPasswordField输入时字符会以屏蔽字符的
类型表示。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField1{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField1");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField();
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setPreferredSize(t1.getPreferredSize());
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
我们可以看到默认的字符串都以屏蔽字符"*"来表示,"*"字符是JPasswordField默认的屏蔽字符,我们可以利用JPasswordField
提供的setEchoChar()方法来改用其他字符来作为屏蔽字符。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField2{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField2");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,2));
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(10);
JPasswordField t2 = new JPasswordField(2);
JPasswordField t3 = new JPasswordField(" 175cm");
JPasswordField t4 = new JPasswordField(" 50kg太瘦了",10);
t1.setEchoChar('#');
t2.setEchoChar('%');
t3.setEchoChar('&');
t4.setEchoChar('M');
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
p1.add(t3);
p1.add(l4);
p1.add(t4);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
9-3-2:利用Document构造JPasswordField:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPasswordField3{
public static void main(String args[]) {
JFrame f = new JFrame("JPasswordField3");
Container contentPane = f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,2));
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; //设定Layout的位置
gbc.insets = new Insets(2,2,2,2); //设定与边界的距离(上,左,下,右)
p1.setBorder(BorderFactory.createTitledBorder("您的基本数据"));
JLabel l1 = new JLabel("姓名:");
JLabel l2 = new JLabel("性别:");
JLabel l3 = new JLabel("身高:");
JLabel l4 = new JLabel("体重:");
JPasswordField t1 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(10),"",10);
JPasswordField t2 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(1),"",2);
JPasswordField t3 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
JPasswordField t4 = new JPasswordField(new JPasswordField3_OnlyNumberDocument(5),"",5);
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Toolkit;
public class JPasswordField3_OnlyNumberDocument extends PlainDocument{
private int maxLength;
int result;
public JPasswordField3_OnlyNumberDocument(int maxLength){
this.maxLength = maxLength;
}
public void insertString(int offset,String str,AttributeSet att) throws BadLocationException
{
for(int i=0;i<=9;i++){
result = Integer.toString(i).compareTo(str);
if (result == 0){ //是数字才处理
if ( getLength() + str.length() > maxLength ){
Toolkit.getDefaultToolkit().beep();
}else{
super.insertString(offset,str,att);
}
}
}
}
}
9-4:使用JTextArea组件:
JTextArea的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JCompontent
--javax.swing.text.JTextComponent
--javax.swing.JTextArea
JTextArea继承JTextComponent为类,因此它也可以使用JTextComponent抽象类里面许多好用的方法,如compy(),paste(),
setText(),isEditable()等等。我们在前面有提到JTextArea是一个多行的输入组件,在这个组件中可以利用Enter来做换行的操作
。
在使用JTextArea之前,我们先看看JTextArea有哪些构造函数可以使用:
JTextArea的构造函数:
JTextArea():建立一个新的JTextArea.
JTextArea(Document doc):使用指定的文件存储模式建立一个新的JTextArea.
JTextArea(Document doc,String text,int row ,int columns):使用指定的文件存储模式建立一个新的JTextArea并设置其初始
字符串和列、字段长度。
JTextArea(int row,int columns):建立一个新的JTextArea并设置其初始列、字段长度。
JTextArea(String text):建立一个新的JTextArea并设置其初始字符串.
JTextArea(String text,int row,int columns):建立一个新的JTextArea并设置其初始字符串和列、字段长度。
9-4-1:构造JTextArea组件:
我们可以发现到JTextArea的构造函数和JTextField及JPasswordField的构造函数是相同雷同,而JTextArea多了一个字段的参数
值是因为JTextArea是二维的输入组件,在构造时不仅要设置字段长度也要设置行数。我们来看下面这个范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea1{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea1");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
gbc.anchor=GridBagConstraints.WEST;
gbc.insets=new Insets(2,2,2,2);
p1.setBorder(BorderFactory.createTitledBorder("构造一般的JTextArea"));
JLabel l1=new JLabel("一:");
JLabel l2=new JLabel("二:");
JLabel l3=new JLabel("三:");
JLabel l4=new JLabel("四:");
JTextArea t1=new JTextArea();
JTextArea t2=new JTextArea(2,8);
JTextArea t3=new JTextArea("JTextArea3");
JTextArea t4=new JTextArea("JTextArea4",5,10);
t1.setText("JTextArea1");//setText()方法会将原来的内容清除
t2.append("JTextArea2");//append()方法会将设置的字符串接在原来JTextArea内容文字之后.
t4.setLineWrap(true);//设置换行
gbc.gridy=1;
gbc.gridx=0;
p1.add(l1,gbc);
gbc.gridx=1;
p1.add(t1,gbc);
gbc.gridy=2;
gbc.gridx=0;
p1.add(l2,gbc);
gbc.gridx=1;
p1.add(t2,gbc);
gbc.gridy=3;
gbc.gridx=0;
p1.add(l3,gbc);
gbc.gridx=1;
p1.add(t3,gbc);
gbc.gridy=4;
gbc.gridx=0;
p1.add(l4,gbc);
gbc.gridx=1;
p1.add(t4,gbc);
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
在JTextArea中我们可以使用setTabSize()方法设置[Tab]键的跳离距离,或是setFont()方法设置字体。当我们输入的文字超过
JTextArea的右边界及下边界时,会看不到接下来打的内容,那该怎么办呢?你可以使用JScrollPane使JTextArea具备滚动的能力,
或是搭配setLineWrap()方法就能让文字自动换行。JTextArea还提供一个setWrapStyleWord()方法,可以让换行的时候不会造成断
字的现象,这在Word或使用OutLook写信时都可以看到这个效果。例如我们在行尾中输入“自动换行”四个字,但此行最多只能在容
纳两个字,因此JTextArea会将此四个字均移到下一行,不会造成“自动”在上行,"换行"在下行的情形。这在处理英文输入上较为
重要,因为setWrapStyleWord()是利用空白当作是一个字输入的结果。我们来看下面的范例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea2{
public static void main(String[] args){
JFrame f=new JFrame("JTextArea2");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("构造TextArea-使用GridLayout,加ScrollBar"));
JTextArea t1=new JTextArea(5,25);
t1.setTabSize(10);
t1.setFont(new Font("标楷体",Font.BOLD,16));
t1.setLineWrap(true);//激活自动换行功能
t1.setWrapStyleWord(true);//激活断行不断字功能
p1.add(new JScrollPane(t1));//将JTextArea放入JScrollPane中,这样就能利用滚动的效果看到输入超过JTextArea高度的
//文字.
contentPane.add(p1);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们再举一个例子,使JTextArea具有copy、paste、cut的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextArea3 implements ActionListener{
JTextArea textarea=null;
JButton b1,b2,b3;
public JTextArea3(){
JFrame f=new JFrame("JTextArea3");
Container contentPane=f.getContentPane();
contentPane.setLayout(new BorderLayout());
textarea=new JTextArea(10,15);
JScrollPane scrollPane=new JScrollPane(textarea);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(1,3));
b1=new JButton("Copy");
b1.addActionListener(this);
b2=new JButton("Paste");
b2.addActionListener(this);
b3=new JButton("Cut");
b3.addActionListener(this);
panel.add(b1);
panel.add(b2);
panel.add(b3);
contentPane.add(scrollPane,BorderLayout.CENTER);
contentPane.add(panel,BorderLayout.SOUTH);
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
new JTextArea3();
}
public void actionPerformed(ActionEvent e){
if (e.getSource()==b1){
textarea.copy();
}
if (e.getSource()==b2){
textarea.paste();
}
if (e.getSource()==b3){
textarea.cut();
}
}
}
9-4-2:JTextArea的事件处理:
由于JTextArea是一个二维的输入组件,因此[Enter]键在JTextArea中代表的意义只是单纯的换行字符而不再是一个事件驱动的
切入点。那么我们该 如何来处理JTextArea的事件呢?还记得我们在前面介绍过Listener的机制吗?相同的,我们一样需要使用
Listener的机制来处理发生在JTextArea中的事件,只是不再是以前提到的ActionListener了。在JTextArea中使用的Listener有两
种,一个是UndoableEditListener,另一个是DocumentListener.UndoableEditListener interface是负责纪录JTextArea中所有操作
发生的顺序并且可以运行还原上一步的功能。这个功能在目前的软件中应用相当广泛,如文书编辑软件Word中的复原功能、小画家
中的复原功能,相信大家都有使用过。DocumentListener interface则是纪录发生在JTextArea中所有的事件(如键入字符、删除
字符、剪下、贴上)并将所有的事件以树状的层次式结构组织起来;也就是说当JTextArea中的内容有任何变动时,会DocumentEvent
,此时必须使用DocumentListener接口中的方法来处理此事件。我们来看下面这个范例,使JTextArea具有复原的功能:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*由于会使用到复原和事件驱动功能,因此需要将javax.swing.undo和javax.swing.event两个package包含进来
*/
import javax.swing.undo.*;
import javax.swing.event.*;
/*JTextArea4类继承JFrame类并实作UndoableEditListener interface.实作UndoableEditListener interface就必须要编写其中的
*undoableEditHappened().
*/
public class JTextArea4 extends JFrame implements UndoableEditListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea4(){
super("JTextArea4");
jta = new JTextArea();
jta.getDocument().addUndoableEditListener(this);//将JTextArea加入UndoableEditListener.
message = new JTextArea();
message.setEditable(false);//利用setEditable()方法将另一个JTextArea设置为不可编辑.
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
//--begin:分别将两个JTextArea通过JPanel放到JFrame中。
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
//--end
//建立目录菜单并放置到JFrame中.
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();//构造目录菜单
setJMenuBar(bar);
setSize(300,300);
//采用inner class方式,分别构造菜单选项被点选后的运行操作。分别调用undo(),redo()方法来完成.
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();//运行undo功能
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();//运行redo功能
message.append("- Redo -\n");
}
});
}//end of JTextArea4()
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
/*当用户在Text Area中有所操作时,就可以用getEdit()方法取得UndoableEdit对象,此对象纪录着刚刚用户的操作,因
*此可由些对象的undo()或redo()达到取消或复原的功能.
*/
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
//判断是否此时是否可以运行undo或redo的功能,并且改变目录菜单的状态值.
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public static void main(String args[]) {
JFrame f = new JTextArea4();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.show();
}//end of main()
}//end of class JTextArea4
我们在前面提到Enter键在JTextArea中不再是事件驱动的切入点,因此我们要利用Listener的机制来控制JTextArea的事件驱动
。但是,我们要怎么样知道在JTextArea中的数据内容呢?这就要了解JTextArea的存储模式了,JTextArea把输入区内的每一行当成
一个独立的单无(Element),并依照Document内规划的树状结构来存储,也就是说在JTextArea的第一行属于Element 0、第二行属于
Element 1、第三行属于Element 2等等。不论我们在费心的去处理。接下来我们来看看,Element和DocumentListener interface的
用法。我们改写JTextArea4.java加入DocumentListener,将程序存储为JTextArea5.java.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.undo.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class JTextArea5 extends JFrame implements UndoableEditListener,DocumentListener{
private UndoableEdit edit;
private JTextArea jta;
private JTextArea message;
private JMenuItem undoitem;
private JMenuItem redoitem;
public JTextArea5(){
super("JTextArea");
jta=new JTextArea();
jta.getDocument().addUndoableEditListener(this);
jta.getDocument().addDocumentListener(this);
message = new JTextArea();
message.setEditable(false);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
p1.setBorder(BorderFactory.createTitledBorder("Edit Area"));
p1.add(new JScrollPane(jta));
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1,1));
p2.setBorder(BorderFactory.createTitledBorder("Message"));
p2.add(new JScrollPane(message));
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(p1);
getContentPane().add(p2);
JMenuBar bar = new JMenuBar();
JMenu theMenu = new JMenu("Edit");
undoitem = new JMenuItem("Undo");
redoitem = new JMenuItem("Redo");
theMenu.add(undoitem);
theMenu.add(redoitem);
bar.add(theMenu);
updateMenuItem();
setJMenuBar(bar);
setSize(300,300);
undoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.undo();
updateMenuItem();
message.append("- Undo -\n");
}
});
redoitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
edit.redo();
updateMenuItem();
message.append("- Redo -\n");
}
});
} //end of JTextArea5
public void undoableEditHappened(UndoableEditEvent ev){
StringBuffer buf = new StringBuffer(200);
edit = ev.getEdit();
buf.append("undoableEdit:");
buf.append(edit.getPresentationName());
buf.append("\n");
message.append(buf.toString());
updateMenuItem();
}//end of undoableEditHappened()
public void updateMenuItem(){
if (edit != null){
undoitem.setEnabled(edit.canUndo());
redoitem.setEnabled(edit.canRedo());
undoitem.setText(edit.getUndoPresentationName());
redoitem.setText(edit.getRedoPresentationName());
}else{
undoitem.setEnabled(false);
redoitem.setEnabled(false);
undoitem.setText("Undo");
redoitem.setText("Redo");
}
}//end of updateMenu()
public void showDE(DocumentEvent de){
StringBuffer debuf=new StringBuffer(100);
debuf.append(de.getType());
debuf.append("Offset:");
debuf.append(de.getOffset());
debuf.append("Length:");
debuf.append(de.getLength());
Element Eroot=jta.getDocument().getDefaultRootElement();
DocumentEvent.ElementChange Echange=de.getChange(Eroot);
if (Echange==null) {
debuf.append("(No Element Change)");
}else{
debuf.append("Element Change:index");
debuf.append("Echange.getIndex()");
}
debuf.append("\n");
message.append(debuf.toString());
}
public void changedUpdate(DocumentEvent de){
showDE(de);
}
public void insertUpdate(DocumentEvent de){
showDE(de);
}
public void removeUpdate(DocumentEvent de){
showDE(de);
}
public static void main(String[] args){
JFrame f=new JTextArea5() ;
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.show();
}
}
9-5:使用JEditorPane组件:
JEditorPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
JEditorPane继承JTextComponent类,因此它也可以使用JTextComponent抽象类里面的方法。JEditorPane的最主要功能在于展
现不同类型的文件格式内容。JEditorPane支持的文件类型有三种:第一种是纯文本类型,其类型的表示法为"text/plain",这种类型
的文件就是我们最常使用的txt文件,这类型的文件可以用记事本或WordPad等文书编辑软件来编辑。第二种是RTF类型,其表示法
为"text/rtf",这种类型的文件特色是能对文字内容做字体缩放、变形、上色等特殊效果。第三类是HTML类型,也就是我们在网络上
所浏览的网页类型,其表示法为"text/html",这类文件的特色相信大家都非常的清楚,除了在对字体效果的表现之外还具有在文件
内加入图片、超级链接等相关功能。但是JEditorPane并不是一个全功能的Web Browser,它仅能支持简单的HTML语法.JEditorPane支
持HTML类型的文件最主要的用途是用来制作在线辅助说明文件。
JEditorPane构造函数:
JEditorPane():建立一个新的JEditorPane.
JEditorPane(String url):以详细的URL字符串为基础来建立一个JEditorPane。
JEditorPane(String type,String text):建立一个被指定字符串text并指定初始化JEditorPane的类型。
JEditorPane(URL initialPage):以详细的URL字符串当作输入值来建立一个JEditorPane.
9-5-1:构造JEditorPane组件:
我们将一个HTML文件放在构造完成的JEditPane中:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane1{
public static void main(String[] args){
JEditorPane editPane=null;
try{
File file=new File("docs/JEditorPane_1.html");
String str=file.getAbsolutePath();//取得文件位置的绝对路径
str="file:"+str;//将绝对路径合成一完整的输入字符串
/*利用setPage()方法将字符串中路径所指的文件加载JEditorPane.
*在setPage()方法中,输入的数据是String类型的字符串,其实这样的构造方式等同于利用JEditorPane的另一个构造函数
*JEditorPane(String str)来构造。因此如果我们将下面两行程序改写如下行:
* editPane=new JEditorPane(str);
*会得到相同的效果,所以我们就不再对此种构造方式再多加说明.
*/
editPane=new JEditorPane();//构造一个空的JEditorPane
editPane.setPage(str);
}catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
/*利用setEditable()方法将JEditorPane设为不可编辑.请注意,这行是相当重要的,若是我们将这个方法设为true,我们将会
*失去HTML文件本身的特性,如超级链接的功能等等。因此我们在使用下面JEditorPane2的例子时,一般都会将编辑的功能取
*消(设置false).目前这个超级链接功能并没有作用,这部份将在JEditorPane的事件处理中介绍.
*/
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane1");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,200);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
我们在前面提到JEditorPane支持三种类型的文件格式,在上面的例子里我们并没有看到设置文件格式的步骤,那是因为在上面
的构造方法中系统会依照输入文件名称来自动判别文件类型。若是我们想要自己设置文件类型可利用setContentType()方法,或是
直接在JEditorPane构造函数中设置。如下面这个范例:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class JEditorPane2{
public static void main(String[] args){
String str=new String("This is a test.\nthis is Line2!\nThis is Line 3!");
JEditorPane editPane=new JEditorPane("text/plain",str);
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane2");
f.setContentPane(new JScrollPane(editPane));
f.pack();
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
以URL类当作JEditPane的参数来构造,但是要注意的地方是使用这种方式来构造里,计算机要连接上局域网络或网际网络不然
程序会找不到URL指定的位置而产生Exception使得程序无法动作.我们来看下面的范例吧!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class JEditorPane3{
public static void main(String[] args){
JEditorPane editPane=null;
try{
URL address=new URL("http://www.sina.com.cn");
editPane=new JEditorPane(address);
}catch(MalformedURLException e){
System.out.println("Malformed URL:"+e);
}catch(IOException e){
System.out.println("IOException:"+e);
}
editPane.setEditable(false);
JFrame f=new JFrame("JEditorPane3");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
9-5-2:JEditorPane的事件处理:
在JEditorPane文件中最常用到事件处理的部份就是HTML文件,那是因为HTML文件本身具有超级链接的功能来做文章链接的用途
。大家还记得我们这一节的第一个范例吗?我们不是加载了一份HTML文件到JEditorPane中吗?虽然画面上都有确实的将超级链接和
图片信息展现出来,可是你有没有发现当你想要点选超级链接的地方时却没有反应呢?那是因为我们并没有在JEditorPane中加入事
件处理机制的缘故。我们改写JEditorPane1.java加入事件处理机制,使JEditorPane具有正常的超链接功能。如下范例:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.awt.event.*;
public class JEditorPane4{
public static void main(String[] args){
JEditorPane editPane = null;
try{
File thef = new File ("docs/JEditorPane_1.html");
String str = thef.getAbsolutePath();
str = "file:"+str;
editPane = new JEditorPane();
editPane.setPage(str);
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
System.exit(0);
}
editPane.setEditable(false);
final JEditorPane thePane = editPane;
//采用inner class的方式编写触发超级链接事件时的对应操作类
editPane.addHyperlinkListener(new HyperlinkListener(){
public void hyperlinkUpdate(HyperlinkEvent hle){//覆写hyperlinkUpdate()方法,当超级链接事件触发时会进入这
//个区段运行.
try{
//判断是否为超级链接运行操作。若操作为真,则将新的HTML文件放到JEditorPane中,
//操作为(thePane.setPage(hle.getURL());)
if (hle.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
}
catch(IOException ioe){
ioe.printStackTrace(System.err);
}
}
});
JFrame f = new JFrame("JEditorPane4");
f.setContentPane(new JScrollPane(editPane));
f.setSize(200,250);
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}//end of main()
}//end of class JEditPane1
另外,若是我们是在纯文字模式(Plain Text)或RTF模式(RTF Text)下需要事件处理模式又该怎么办呢?你还记得我们在
JTextArea中是如何加入事件处理模式的吗?没错!在JEditorPane中也是相同的做法,也就是利用DocumentListener interface的
机制来处理,由于做法相当类似,因此我们就不在这里重复的说明.
9-6:使用JTextPane组件:
JTextPane的类层次结构图:
java.lang.Object
--java.awt.Component
--java.awt.Container
--javax.swing.JComponent
--javax.swing.text.JTextComponent
--javax.swing.JEditorPane
--javax.swing.JTextPane
我们在前面有介绍过JTextArea类,虽然JTextArea在某些功能上已经能够满足我们的需求,但是当我们想再加入更多的变化时
(如文字加入色彩、插入图片...)就会发现JTextArea类根本无法做到。要做到这些功能,我们必须使用JEditorPane的子类:
JTextpane。JTextPane提供了许多对文字的处理,如改变颜色、字体缩放、文字风格、加入图片等。我们先来看看JTextPane的构
造方法:
JTextPane构造函数:
JTextPane():建立一个新的JTextPane.
JTextPane(StyledDocument doc):以指定的文件模式建立一个新的JTextPane.
9-6-1:JTextPane的特性:
相信大家都有用过Word来写过报告或文章,那么你一定会知道我们在Word中可以对文章中的文字做很多的变化,这些变化都是
属于文字的“属性”变化。由于在JTextPane中产生的效果几乎都是由属性的变化而来,所以改变属性的类组件在JTextpane中是少
不了的。因此在介绍如何构造JTextPane之前,我们要先介绍两个在JTextPane中常用到属性类:
SimpleAttributeSet和StyleConstant.
属性的变化原本是利用AttributeSet interface来处理的,但是这个interface中包含了太多的方法,若是我们直接实作
AttributeSet interface那就需要实作此interface里所有的方法,这对编写程序来说并不是一个很理想的做法;而java另外提供了
SimpleAttributeSet类,实作了AttributeSet interface.因此,只要我们直接使用SimpleAttributeSet类就能具备AttributeSet
interface的所有功能,而不用一个个的编写AttributeSet中的方法。另外StyleConstant类则是提供AttributeSet类许多常用的属
性键值(Attribute Key)和方法来设置或取得JTextPane内容的状态。在StyleConstant类中包含了许多的常用的属性设置,包括本文
与边界空白区段设置、文字字体/大小/类型设置、背景颜色设置等。利用这两个类来辅助设计JTextPane便使JTextPane有更丰富
的内容变化。
JTextPane是专为文字和版面处理设计的组件。JTextPane对可输入区域内容的设计概念是一个类似Word的设计概念,也就是说在
JTextPane中的文字结构是有段落概念的。“段落”的概念就是以[Enter]键为每一段落的分界点,每按一次[Enter]键就增加一个段
落。记得我们在JTextArea中提过的Element存储模式吗?在JTextPane中也是采用相同的做法,但是差别在于规划存储的方式不同。
在JTextArea中并没有分段落,只是单纯的以[Enter]键当作存储成两个Element的分界。而在JTextPane则是以整个编辑区哉为根节
点,每个段落为枝节点 ,每个字符为叶节点来存储文件。也因为JTextPane是采用这样的方式来存储数据,因此在JTextPane中也可
以像Word文件一样将各个段落设置成不同的属性,如第一段为斜体字、字体大小为14号字、粗体字,第二段为斜体字、字体颜色为
蓝色、向左边界缩排2厘米等;另外,我们还可以设置JTextPane编辑区内输入的文字与各个边界间的距离。由这些功能看来,对于一
个TextComponent来说JTextPane是一个具有相当多实用功能的组件。
9-6-2:构造JTextPane组件:
在了解JTextPane的各项特性之后,我们现在马上来看JTextPane可以呈现什么样的效果,在下面这个例子中我们将对JTextPane
区域内的文字设置颜色、粗斜体、与底线等相关属性。
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.*;
public class JTextPane1{
private JTextPane textPane;
public JTextPane1(){
textPane=new JTextPane();
textPane.setBackground(Color.black);
textPane.setEditable(false);
}
public void setYellow_Bold_20(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.yellow);
StyleConstants.setBold(attrset,true);
insert(str,attrset);
}
public void setBlue_Italic_Bold_22(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.blue);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
public void setRed_UnderLine_Italic_24(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
StyleConstants.setForeground(attrset,Color.red);
StyleConstants.setUnderline(attrset,true);
StyleConstants.setItalic(attrset,true);
StyleConstants.setFontSize(attrset,24);
insert(str,attrset);
}
//这个方法最主要的用途是将字符串插入到JTextPane中。
public void insert(String str,AttributeSet attrset){
Document docs=textPane.getDocument();//利用getDocument()方法取得JTextPane的Document instance.0
str=str+"\n";
try{
docs.insertString(docs.getLength(),str,attrset);
}catch(BadLocationException ble){
System.out.println("BadLocationException:"+ble);
}
}
public Component getComponent(){
return textPane;
}
public static void main(String[] args){
JTextPane1 pane=new JTextPane1();
pane.setYellow_Bold_20("This is Line 1,yellow,Bold,Size 20");
pane.setBlue_Italic_Bold_22("This is Line 2,blue,Italic,Bold,Size 22");
pane.setRed_UnderLine_Italic_24("This is Line 3,red,UnderLine,Italic,Size 24");
JFrame f=new JFrame("JTextPane1");
f.getContentPane().add(pane.getComponent());
f.setSize(450,180);
f.show();
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
若你想在JTextPane上置入图形或其他组件(如表格或按钮),你可以分别使用JTextPane所提供的insetIcon()与insertComponent()
方法来达到这个效果。
至于另外一种JTextPane的构造方式和JTextArea一样,差别在于JTextArea是采用Document interface而JTextPane是采用
Saturday, 5 May 2007
Saturday, 28 April 2007
may_pre
网线,10米至20米
电饭锅,全自动
西装, 体恤
文具
味精
无线网卡
大箱子
CD, 耳机
药,花露水
雨伞
有中国特色的小礼物
NOTTINGHAM有泡面卖,有一个PAND SHOP.经常去CHECK学校邮箱,多留意学校上课网,根据前几年的试卷来推测本年的考试题,多做笔记.
尽量和外国人住在一起
出去以前去于谦那里拿PAY AS YOU GO SIM CARD
问清各个学科所占比例,各个学年所占比例.
有空去爱丁堡和伦敦走走
银行卡的办理需要1个月左,很多东西需要根据银行卡
http://blog.sina.com.cn/u/4cacf58b010009ip
一、随身行李(6公斤,手提电脑除外)
基本随身物品:
护照
Offer
体检证明 : 《国际旅行健康证明书》和《国际预防接种证书》
机票 ( 请提前一个月预定 )
护照 / 签证 /Offer 的复印件,要和原件分开放。
护照大小的免冠照片 ( 带 20 张以上 2 寸,到了英国用的地方很多 ) 。
现金,随身携带 100 英镑或多少不等的现金以备急需。 ( 如果可能带 10 镑左右的硬币,在机场打电话用, Heathrow 机场的电话很多只能打出不能打进的。 )
紧急联络电话,包括学校、系、导师的电话等。还有家庭亲戚同学朋友联系方式,电子版本.
你在英国的机场入境时,入境官员和卫生官员会要求你出示以上文件,因此应将其放在随身携带的手提包中,以方便取出。除此之外,还需要填写入境登记卡,此卡由乘务员在飞机快着陆时发放。
其他随身物品:(飞机上的同胞应该不少,有什么需要帮助的尽管提出。)
如有晕车晕机历史的,携带晕机药。
雨伞 ( 或者雨衣,放在托运行李中即可,但是要放在比较好拿出来的地方 ) 。
电子词典 ( 因人而异 ) 。
笔和记事本,到达英国入境时要用。
地图 ( 可在机场的 Information Centre 拿一份 ) 。
现金:相当于 5000 美金的英镑,大概 2800 英镑。
其他日用品:洗面液,面巾纸,女孩子的各类化妆品, CD 、 MP3 、小说等等。
二、托运行李 ( 30 公斤 , 长宽高之和不超过 158 公分的行李箱)
不要忘记清楚标识你的行李 , 把你的姓名和在英联系方式写在标签上。
1 、 衣 :内衣,袜子
春秋:防雨夹克,薄毛衣,长袖衫, 牛仔裤 ,绒衣,( 英国穿毛衣的机会多)
夏:体恤衫(长袖,短袖),短裤,脱鞋,凉鞋.
冬:厚毛衣, 羽绒服,夹克,皮衣, 薄毛裤,羽绒背心,围巾,手套 ,帽子等
正装:西服,衬衫(长,短),领带, 唐装(英国穿正装的机会不多)
2 、 鞋 : 运动鞋 ,皮鞋,拖鞋
3 、 食 :花椒,大料,木筷(勺),水果刀,电饭煲,热得快,牙签,茶叶,菜刀,
4 、 药 :感冒类药(39冲剂), 花露水, 皮眼平,黄莲上清丸,螺旋霉素,胃药,皮炎平,云南白药,清凉油,风油精,晕车药,止疼片,跌打损伤药,退烧药等。(但千万不要带中草药)
5 、 住 :牙膏,牙刷,洗头水(小袋),指甲刀,耳勺,剪刀, 指甲刀,透明胶,床单,被罩 , 枕套 , 毛巾 , 浴巾 , 睡衣 , 刮胡刀 , 眼镜 , 手电 , 梳子 , 小镜子 , 蚊香 , 卫生球 , 干燥剂 ,
6 、 眼镜: 近视眼镜(除现戴的再备一副);隐形眼镜(两副);护理液(两瓶)太阳镜;眼药水;
7 、 其他 : 电池 ( 最好是充电电池,英国电池很贵 ) 和充电器。小电器,如 MD 、 Discman 、 Walkman 、电动剃须刀(最好可直接充电的)、闹钟等。相机(较多胶卷或数码相机)。
书籍一类要有选择的带,毕竟占重量也占空间,词典一类的工具书和必要的专业书籍即可,如果非要带很多的话最好单独办理邮寄,或者海运也好。
移动硬盘,刻录光盘。 (一般是无人过问的)
礼品。礼品无需很贵重,诸如茶叶、中国邮票就可以了。 CD 可以拿一些中国传统乐器的 ( 包装好一点 , 送老外很好的礼品 ) 。最后还可以带两条烟过来。
可选项:(适合长期居住,纨绔一族的)
DVD Player( 全区解码 ) 、电火锅、豆浆机、麻酱或火锅调料等。有线电话。
小结:大多数的东西是可以在这边买的到的。只是价钱有的差别大一些,有的小一些。目前为止发现买不到的只有韭菜花。
注意:机场现在对行李超重检查的很严格的,不要存在侥幸心理,打无准备之仗。
三、体检信息
" 体检时间:您可以在签证前或签证后体检(体检通常需要三到五个工作日出结果,请注意体检当天应空腹,带上本人身份证,外地学生也可在北京体检)。
" 体检地点:请您到居住地所在地的检验检疫局体检(使馆无体检表),或者到北京出入境检验检疫局保健中心体检,办理《国际旅行健康证明书》和《国际预防接种证书》。
北京出入境检验检验局保健中心:授权发放健康卡(也叫黄皮本)的机构。
位于和平里北街 20 号,和平里医院旁边。在灯市口车站乘坐 104 快车,蒋宅口下车即是。电话: 64274240—8 。每天上午体检。
收费: 400 元左右 RMB
" 体检的作用:方便出境抽查。这是入境的最后一关。如被抽查到,出示健康卡,即可通过;如没有健康卡,将被要求做临时体检。(在英国居留 6 个月以上,应有健康卡)
http://blog.sina.com.cn/u/4cacf58b010009in
图书馆:藏藏书100多万册,5000余种期刊;图书馆年资料经费支出为平均每位全日制学生40英镑。
计算机资源:设有学术计算机服务网,所有学生宿舍均可接通。
旅行:夜间无偿提供学生去图书馆和吧的小型公共汽车,校园有车直通车站、机场和码头。还有自行车租赁
http://blog.sina.com.cn/zliybwc#feeds_FEEDS_1286403467
服饰
外套:至少要有一件到两件带帽子, 防水性好的, 可以当雨衣用. 冬天的英国雨水充足, 而且说不定什么时候就下雨, 这样的衣服会非常实用!
毛衣: 一到两件; 英国冬天的感觉与大陆不同; 由于房间里暖气的充足, 在户外活动时间的短暂, 决定了毛衣不象国内般流行. 就是在最冷的冬天, 很多人都是外头一件厚实的外套,里面一件薄的毛衣. 如果有条件最好带羊绒制品, 薄而御寒.
毛裤秋裤: 基本不用; 但如果实在怕冷可以带一条来, 但你会瞬间发现是多么的无用.
外裤: 一般长裤即可, 但最好有一条很厚实的, 在最冷的时候穿.
袜子: 厚实保暖类.
手套: 厚的手套在英国非常必需.
围巾: 最好两条,因为到了十二月到二月期间, 围巾几乎要天天带, 多一条没坏处.
帽子: 绝对需要; 要棉的那种, 把耳朵都遮上, 尤其如果你要骑车, 没有帽子会冷得你头疼.
内衣
春夏服饰(之所以把春天和夏天列在一起是考虑到英国的最热都不过20度, 在国内看来都算是三到五月的春天.):
外衣: 薄风衣; 在微寒的春天早晨还是需要的; 同样需要带帽子和防水的.
各种男式或女式衬衫/ T恤; 长袖也要考虑, 毕竟英国十几度的白天是很普遍的.
帽子: 夏天太阳也会很大, 带个运动帽可以保护你的脸不晒黑, 而且尽显青春风采!
袜子: 薄一些的运动袜
鞋: 运动鞋一双, 拖鞋一双; 皮鞋一双(鞋油);
运动服: 喜欢运动的朋友可以带一到两套;
洗涤用品
我个人不主张在本身重量就不富裕的行囊中携带太多的洗涤用品. 因为这种东西很占份量,而且消耗很快, 不可能一次就带够一年用的, 最终还是得在英国本地买. 在英国最便宜的洗衣粉1.215KG才70多P, 合人民币8元多. 而TESCO values包装的六块装肥皂也不超过1镑. 而其他洗碗什么的洗涤剂就更没必要大老远从中国运来了, 大多数学生宿舍公用厨房都应该配备有.
个人卫生用品( 记住上面的原则, 够刚到的几天的即可):
牙杯
牙刷
小管装牙膏(大管比较重)//防上火, 中华中草药
香皂
香皂盒
洗发水
洗面奶
毛巾(多备几条, 英国毛巾较贵)
厨房用品
刀具: 一把锋利的水果刀; 喜欢自己剁东西的朋友可以考虑带把菜刀.
杯子: 一般的喝水杯
筷子; 最好带两到三双; 根据本人经验, 很多中国朋友吃饭都需要客人自带碗筷, 可见主人准备不充足.哈哈!
勺子
叉子
塑料饭盒; 非常实用, 一可以替代碗碟, 二可以装便当带到学校或工作地方, 尤其是那些不包餐的PART TIME工作.
圆底锅: 炒菜很需要
炒菜勺
碗(塑料, 适合微波炉用, 而且重量轻.)
盘子(塑料, 适合微波炉用, 而且重量轻.)
床上用品
床单;两套, 可以换洗.
枕套;
背罩.
其他
面霜
橡皮筋
针线盒; 此物英国昂贵, 最好自备.
电子塑料闹钟
指甲剪
小镜子
梳子
雨伞
CD(多张)(带你最爱的歌,以缓解乡愁)
太阳镜
眼镜盒
插头转换头
相机
收音机
衣架//自己做, 但需要夹子
软盘(可以把重要的学习资料或各种数据储存在里面, 非常有用! 尤其对那些没有自带电脑的朋友)
学习用品
书包(双肩背或挎包都可以, 但后者在英国比较流行.)
文具盒或笔袋
笔(若签字笔,圆珠笔、铅笔、铅芯, 如需要钢笔则要考虑灌墨问题.)
橡皮
刀片
直尺
电子字典,如快译通或文曲星(听很多网友都推荐文曲星PC505型号,物美价廉)
录音笔/录音机; 如果你怕听课有困难, 可以带一支录音笔.
磁带
充电器/充电电池(5号和7号)
计算器
涂改液
笔记本
讲义夹
钉书器
打孔机; 在纸张上打小圆孔, 方便存放在文件夹
胶水
透明胶
牛津或郎文双解英汉字典
汉英字典
注意: 如果是学ENGINEERING, ARCHITECTURE或ART的学生, 则另外需要带一些学习用品, 包括圆规, 特殊尺笔或颜料等, 来之前最好查询清楚. 因为这样的用品在英国会很昂贵!
药物
·体温表·橡皮膏 ·医用棉花 ·医用剪刀·医用镊子·医用纱布注意:以上物件务必使用医用类型,以保证卫生。药品:尤其注意的是: 感冒退烧药品需要多带, 由于英国感冒症状非常常见,且容易传染.抗过敏及消炎药品也需常备.分类药名作用退烧类药物阿思匹林
呼吸系统常用药物康泰克用于感冒
速效伤风胶囊清热解毒、用于感冒发热
消化系统常用药物胃复安止吐、消除胃涨
胃舒平抗酸、保护溃疡面,用于胃溃疡、胃酸过多、胃痛等
999胃泰
止痛药芬必得
万应止痛膏
解热止痛片
牙痛一粒丸治牙痛
抗过敏息斯敏
扑尔敏过敏性疾病、伤风流涕、药物过敏等
外用药创可贴止血、消炎、护创
紫药水杀菌,用于皮肤、粘膜感染及溃疡
皮康霜
皮炎平用于皮肤瘙痒
云南白药用于跌打损伤
驱风油
四环素软膏抗菌排脓,用于痤疮、皮炎、冻疮、烫伤、烧伤
诺氟沙星滴眼液多种病原菌引起的外眼部感染,如角膜炎、结膜炎等
盐酸环丙沙星滴眼液用于眼睛疾病
正红花油烫伤、蚊虫叮咬
达克宁霜用于治疗脚气等
消炎、消火牛黄解毒片
西瓜霜润喉片清音利咽、消肿止痛
最后需要注意的是: 任何衣物都要保证不缩水; 因为这里的衣服基本都是烘干, 不是自然晾晒干
护照(签证)(均要复制两份,一份随身,一份留家中)
入学通知(均要复制两份,一份随身,一份留家中)
机票钱(包括零钱)
体检证明(包括接种证明、小药箱)
其他文件(如成绩单、学位证书、推荐信,均要复制两份,一份随身,一份留家中)
护照照片 (最好使用白色背景)
接机人姓名、电话
在英亲戚朋友通信录
紧急联络电话
我国驻当地大使馆、商务办事处电话。
前两天生活用品(换洗内衣裤一套、药品、纸笔、眼镜、牙刷牙膏、毛巾、手纸)
Friday, 27 April 2007
hashtable
Hashtables(哈希表)在计算机领域中已不是一个新概念了。它们是用来加快计算机的处理速度的,用当今的标准来处理,速度非常慢,而它们可以让你在查询许多数据条目时,很快地找到一个特殊的条目。尽管现代的机器速度已快了几千倍,但是为了得到应用程序的最佳性能,hashtables仍然是个很有用的方法。
设想一下,你有一个包含约一千条记录的数据文件,比如一个小企业的客户记录,还有一个程序,它把记录读到内存中进行处理。每个记录包含一个唯一的五位数的客户ID号、客户名字、地址、帐户结余等等。假设记录不是按客户ID号顺序分类的,所以,如果程序要将客户ID号作为“key” 来查找一个特殊的客户记录,唯一的查找方法就是连续地搜索每个记录。有时侯,它会很快找到你需要的记录;但有时侯,在程序找到你需要的记录前,它几乎已搜索到了最后一条记录。如果要在1,000条记录中搜索,那么查找任何一条记录都需要程序平均查核500.5 ((1000 + 1 )/2)条记录。如果你常需要查找数据,你应该需要一个更快的方法来找到一条记录。
一种加快搜索的方法就是把记录分成几段,这样,你就不用搜索一个很大的列表了,而是搜索几个短的列表。对于我们数字式的客户ID号,你可以建10个列表,以0开头的ID号组成一个列表,以1开头的ID号组成一个列表,依此类推。那么要查找客户ID号38016,你只需要搜索以3开头的列表就行了。如果有1,000条记录,每个列表的平均长度为100(1,000条记录被分成10个列表),那么搜索一条记录的平均比较次数就降到了约50(见图1)。
当然,如果约十分之一的客户号是以0开头的,另外十分之一是以1开头的,等等,那么这种方法会很适合。如果90%的客户号以0开头,那么那个列表就会有900条记录,每次查找平均需要进行450次比较。另外,程序需要执行的搜索有90%都是针对以0开头的号码的。因此,平均比较数就大大超过简单数学运算的范围了。
如果我们可以按这样一种方式在我们的列表中分配记录,情况就会好一些,即每个列表约有相同条目的记录,而不管键值中数字的分布。我们需要一种方法能够把客户号码混合到一起并更好地分布结果。例如,我们可以取号码中的每位数,乘以某个大的数(随着数字位置的不同而不同), 然后将结果相加产生一个总数,把这个数除以10,并将余数作为索引值(index)(除数相同的分到一组)。当读入记录时,程序在客户号码上运行这个哈希(hash) 函数来确定记录属于哪个列表。当用户需要查询时,将同一个哈希函数作为一个“key”用于客户号码,这样就可以搜索正确的列表了。 像这样的一个数据结构就称为一个哈希表(hashtable)。
Java中的Hashtables
Java包含两个类,java.util.Hashtable 和java.util.HashMap,它们提供了一个多种用途的hashtable机制。这两个类很相似,通常提供相同的公有接口。但它们的确有一些重要的不同点,我在后面会讲到。
Hashtable和HashMap对象可以让你把一个key和一个value结合起来,并用put() 方法把这对key/value输入到表中。然后你可以通过调用get()方法,把key作为参数来得到这个value(值)。只要满足两个基本的要求,key和value可以是任何对象。注意,因为key和value必须是对象,所以原始类型(primitive types)必须通过运用诸如Integer(int)的方法转换成对象。
为了将一个特定类的对象用做一个key,这个类必须提供两个方法,equals() 和 hashCode()。这两个方法在java.lang.Object中,所以所有的类都可以继承这两个方法;但是,这两个方法在Object类中的实现一般没什么用,所以你通常需要自己重载这两个方法。Equals()方法把它的对象同另一个对象进行比较,如果这两个对象代表相同的信息,则返回true。该方法也查看并确保这两个对象属于相同的类。如果两个参照对象是完全一样的对象,Object.equals()返回true,这就说明了为什么这个方法通常不是很适合的原因。在大多数情况下,你需要一个方法来一个字段一个字段地进行比较,所以我们认为代表相同数据的不同对象是相等的。
HashCode()方法通过运用对象的内容执行一个哈希函数来生成一个int值。Hashtable和HashMap用这个值来算出一对key/value位于哪个bucket(哈希元)(或列表)中。作为例子,我们可以查看一下String 类,因为它有自己的方法来实现这两个方法。String.equals()对两个String对象一个字符一个字符地进行比较,如果字符串是相同的,则返回true:
String myName = "Einstein";
// The following test is
// always true
if ( myName.equals("Einstein") )
{ ...
String.hashCode()在一个字符串上运行哈希函数。字符串中每个字符的数字代码都乘以31,结果取决于字符串中字符的位置。然后将这些计算的结果相加,得到一个总数。这个过程似乎很复杂,但是它确保能够更好地分布值。它也证明了你在开发你自己的hashCode()方法时,能够走多远,确信结果是唯一的。
例如,假设我要用一个hashtable来实现一个书的目录,把书的ISBN号码作为搜索键来进行搜索。我可以用String类来承载细节,并准备好了equals()和hashCode()方法。我们可以用put()方法添加成对的key/value到hashtable中。
Put()方法接受两个参数,它们都属于Object类型。第一个参数是key;第二个参数是value。Put()方法调用key的hashCode()方法,用表中的列表数来除这个结果。把余数作为索引值来确定该条记录添加到哪个列表中。注意,key在表中是唯一的;如果你用一个已经存在的key来调用put(),匹配的条目就被修改了,因此它参照的是一个新的值,而旧的值被返回了(当key在表中不存在时,put()返回空值)。要读取表中的一个值,我们把搜索键用于get()方法。它返回一个转换到正确类型的Object参照:
BookRecord br =(BookRecord)isbnTable.get("0-345-40946-9");
System.out.println("Author: " + br.author+ " Title: " + br.title);
另一个有用的方法是remove(),其用法同get()几乎一样,它把条目从表中删除,并返回给调用程序。
你自己的类
如果你想把一个原始类型用做一个key,你必须创建一个同等类型的对象。例如,如果你想用一个整数key,你应该用构造器Integer(int)从整数中生成一个对象。所有的封装类如Integer、Float和Boolean都把原始值看做是对象,它们重载了equals()和hashCode()方法,因此,它们可以被用做key。JDK中提供的许多其它的类也是这样的(甚至Hashtable和HashMap类都实现它们自己的equals()和hashCode()方法),但你把任何类的对象用做hashtable keys前,应该查看文件。查看类的来源,看看equals()和hashCode()是如何实现的,也很有必要。例如,Byte、Character、Short和Integer都返回所代表的整数值作为哈希码。这可能适合,也可能不适合你的需求。
如果你想创建一个hashtable,这个hashtable运用你自己定义的一个类的对象作为key,那么你应该确信这个类的equals()和hashCode()方法提供有用的值。首先查看你扩展的类,确定它的实现是否满足你的需求。如果没有,你应该重载方法。
任何equals()方法的基本设计约束是,如果传递给它的对象属于同一个类,而且它的数据字段设定为表示同样数据的值,那么它就应该返回true。你也应该确信,如果传递一个空的参数给该方法,那么你的代码返回false:
public boolean equals(Object o){
if ( (o == null)|| !(o instanceof myClass)){
return false;
}
// Now compare data fields...
另外,在设计一个hashCode()方法时,应该记住一些规则。首先,该方法必须为一个特定的对象返回相同的值,而不管这个方法被调用了多少次(当然,只要对象的内容在调用之间没有改变,在将一个对象用做一个hashtable的key时,应该避免这一点)。第二,如果由你的equals()方法定义的两个对象是相等的,那么它们也必须生成相同的哈希码。第三,这更像是一个方针,而不是一个原则,你应该设法设计方法,使它为不同的对象内容生成不同的结果。如果偶尔不同的对象正好生成了相同的哈希码,这也不要紧。但是,如果该方法只能返回范围在1到10的值,那么只能用10个列表,而不管在hashtable中有多少个列表。
在设计equals()和hashCode()时,另一个要记住的因素是性能问题。每次调用put()或get(),都包括调用hashCode()来查找正确的列表,当get()扫描列表来查找key时,它为列表中的每个元素调用equals()。实现这些方法使它们尽可能快而有效地运行,尤其当你打算使你的类公开可用时,因为其它的用户可能想在执行速度很重要的情况下,在高性能的应用程序中运用你的类。
Hashtable性能
影响hashtable功效的主要因素就是表中列表的平均长度,因为平均搜索时间与这个平均长度直接相关。很显然,要减小平均长度,你必须增加hashtable中列表的数量;如果列表数量非常大,以至于大多数列表或所有列表只包含一条记录,你就会获得最佳的搜索效率。然而,这样做可能太过分了。如果你的hashtable的列表数远远多于数据条目,那你就没有必要做这样的内存花费了,而在一些情况下,人们也不可能接受这样的做法。
在我们前面的例子中,我们预先知道我们有多少条记录1,000。知道这点后,我们就可以决定我们的hashtable应该包含多少个列表,以便达成搜索速度和内存使用效率之间最好的折衷方式。然而,在许多情况下,你预先不知道你要处理多少条记录;数据被读取的文件可能会不断扩大,或者记录的数量可能一天一天地发生很大的变化。
随着条目的增加,Hashtable和HashMap类通过动态地扩展表来处理这个问题。这两个类都有接受表中列表最初数量的构造器,和一个作为参数的负载系数(load factor):
public Hashtable(int initialCapacity,float loadFactor)
public HashMap(int initialCapacity,float loadFactor)
将这两个数相乘计算出一个临界值。每次给哈希表添加一个新的条目时,计数就被更新,当计数超过临界值时,表被重新设置(rehash)。(列表数量增加到以前数量的两倍加1,所有的条目转移到正确的列表中。)缺省的构造器设定最初的容量为11,负载系数是0.75,所以临界值是8。当第九条记录被添加到表中时,就重新调整哈希表,使其有23个列表,新的临界值将是17(23*0.75的整数部分)。你可以看到,负载系数是哈希表中平均列表数量的上限,这就意味着,在缺省情况下,哈希表很少会有许多包含不只一条记录的列表。比较我们最初的例子,在那个例子中,我们有1,000条记录,分布在10个列表中。如果我们用缺省值,这个表将会扩展到含有1,500多个列表。但你可以控制这点。如果用负载系数相乘的列表数量大于你处理的条目数,那么表永远不会重制,所以我们可以仿效下面的例子:// Table will not rehash until it
// has 1,100 entries (10*110):
Hashtable myHashTable = new Hashtable(10, 110.0F);
你可能不想这么做,除非你没有为空的列表节省内存,而且不介意额外的搜索时间,这可能在嵌入系统中会出现这种情况。然而,这种方法可能很有用,因为重新设置很占用计算时间,而这种方法可以保证永远不会发生重新设置这种情况。注意,虽然调用put()可以使表增大(列表数量增加),调用remove()不会有相反的结果。所以,如果你有一个大的表,而且从中删除了大部分条目,结果你会有一个大的但是大部分是空的表。
Hashtable和HashMap
Hashtable和HashMap类有三个重要的不同之处。第一个不同主要是历史原因。Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现。
也许最重要的不同是Hashtable的方法是同步的,而HashMapu方法不是。这就意味着,虽然你可以不用采取任何特殊的行为就可以在一个多线程的应用程序中用一个Hashtable,但你必须同样地为一个HashMap提供外同步。一个方便的方法就是利用Collections类的静态的synchronizedMap()方法,它创建一个线程安全的Map对象,并把它作为一个封装的对象来返回。这个对象的方法可以让你同步访问潜在的HashMap。这么做的结果就是当你不需要同步时,你不能切断Hashtable中的同步(比如在一个单线程的应用程序中),而且同步增加了很多处理费用。第三点不同是,只有HashMap可以让你将空值作为一个表的条目的key或value。HashMap中只有一条记录可以是一个空的key,但任意数量的条目可以是空的value。这就是说,如果在表中没有发现搜索键,或者如果发现了搜索键,但它是一个空的值,那么get()将返回null。如果有必要,用containKey()方法来区别这两种情况。
一些资料建议,当需要同步时,用Hashtable,反之用HashMap。但是,因为在需要时,HashMap可以被同步,HashMap的功能比Hashtable的功能更多,而且它不是基于一个陈旧的类的,所以有人认为,在各种情况下,HashMap都优先于Hashtable。
关于Properties
有时侯,你可能想用一个hashtable来映射key的字符串到value的字符串。DOS、Windows和Unix中的环境字符串就有一些例子,如key的字符串PATH被映射到value的字符串C:\WINDOWS;C:\WINDOWS\SYSTEM。Hashtables是表示这些的一个简单的方法,但Java提供了另外一种方法。
Java.util.Properties类是Hashtable的一个子类,设计用于String keys和values。Properties对象的用法同Hashtable的用法相象,但是类增加了两个节省时间的方法,你应该知道。Store()方法把一个Properties对象的内容以一种可读的形式保存到一个文件中。Load()方法正好相反,用来读取文件,并设定Properties对象来包含keys和values。注意,因为Properties扩展了Hashtable,你可以用超类的put()方法来添加不是String对象的keys和values。这是不可取的。另外,如果你将store()用于一个不包含String对象的Properties对象,store()将失败。作为put()和get()的替代,你应该用setProperty()和getProperty(),它们用String参数。好了,我希望你现在可以知道如何用hashtables来加速你的处理了。
关于作者:
Pete Ford已经做了20多年的软件开发工作了,他主要在嵌入系统和turnkey system方面进行研究。他生活并工作于德克萨斯州的达拉斯。你可以通过p_ford@mindspring.com联系他
哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
Java.util.Hashtable提供了种方法让用户使用哈希表,而不需要考虑其哈希表真正如何工作。
哈希表类中提供了三种构造方法,分别是:
public Hashtable()
public Hashtable(int initialcapacity)
public Hashtable(int initialCapacity,float loadFactor)
参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充,例如,有一哈希表,容量为100,而装载因子为0.9,那么当哈希表90%的容量已被使用时,此哈希表会自动扩充成一个更大的哈希表。如果用户不赋这些参数,系统会自动进行处理,而不需要用户操心。
Hashtable提供了基本的插入、检索等方法。
■插入
public synchronized void put(Object key,Object value)
给对象value设定一关键字key,并将其加到Hashtable中。若此关键字已经存在,则将此关键字对应的旧对象更新为新的对象Value。这表明在哈希表中相同的关键字不可能对应不同的对象(从哈希表的基本思想来看,这也是显而易见的)。
■检索
public synchronized Object get(Object key)
根据给定关键字key获取相对应的对象。
public synchronized boolean containsKey(Object key)
判断哈希表中是否包含关键字key。
public synchronized boolean contains(Object value)
判断value是否是哈希表中的一个元素。
■删除
public synchronized object remove(object key)
从哈希表中删除关键字key所对应的对象。
public synchronized void clear()
清除哈希表
另外,Hashtalbe还提供方法获取相对应的枚举集合:
public synchronized Enumeration keys()
返回关键字对应的枚举对象。
public synchronized Enumeration elements()
返回元素对应的枚举对象。
例8.5 Hashtable.java给出了使用Hashtable的例子。
例8.5 Hashtalbe.java。
//import java.lang.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp{
public static void main(String args[]){
Hashtable hash=new Hashtable(2,(float)0.8);
//创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
hash.put("Jiangsu","Nanjing");
//将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
hash.put("Beijing","Beijing");
hash.put("Zhejiang","Hangzhou");
System.out.println("The hashtable hash1 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
//打印hash的内容和大小
Enumeration enum1=hash.elements();
System.out.print("The element of hash is: ");
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
System.out.println();
//依次打印hash中的内容
if(hash.containsKey("Jiangsu"))
System.out.println("The capatial of Jiangsu is "+hash.get("Jiangsu"));
hash.remove("Beijing");
//删除关键字Beijing对应对象
System.out.println("The hashtable hash2 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
}
}
运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 2
Hashtable是Dictionary(字典)类的子类。在字典类中就把关键字对应到数据值。字典类是一个抽象类。在java.util中还有一个类Properties,它是Hashtable的子类。用它可以进行与对象属性相关的操作
http://www.skyabove.cn/article.asp?id=32
enum
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
体验JAVA 5的新增语言特性
enum
In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
Note: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
ref:
Enum Types
掌握JDK1.5枚举类型
Wednesday, 25 April 2007
lecture 7;8;9
lecture 6
Memory-Mapped Input and Output
Within SPIM: console and keyboard are using by CPU to communicate with external devices.
Some MIPS addresses are actually device registers
- Console I/O in SPIM
- SPIM emulates MMIO
- Must select ‘Mapped I/O’ in PCSpim settings
- Receiver – keyboard
- Transmitter – display
- Can still use syscalls
Keyboard Input
- Receiver control (at FFFF000016) consists of 2 bits
- Bit 0 is the ‘ready’ bit – unread input from keyboard
- Receiver data (at FFFF000416) contains last pressed key
- Reading data register resets ‘ready’ bit
- Read from control register
- AND off the ‘ready’ bit
- If zero, no keypress
- Keep waiting
- Else read data register
- li $t0, 0xffff0000
- rd poll:
- lw $v0, 0($t0)
- andi $v0, $v0, 0x01
- beq $v0, $zero, rd poll
- lw $v0, 4($t0)
- # last key code in $v0
Character Display
- Transmitter control (at FFFF000816) consists of 2 bits
- Bit 0 is the ‘ready’ bit – display accepting new character
- Transmitter data (at FFFF000C16) takes ASCII character
- Writing data register resets ‘ready’ bit
- Read from control register
- AND off the ‘ready’ bit
- If zero, not ready
- Keep waiting
- Else send to data register
- # character in $a0
- li $t0, 0xffff0008
- wr poll:
- lw $v0, 0($t0)
- andi $v0, $v0, 0x01
- beq $v0, $zero, wr poll
- sw $a0, 4($t0)
half-adder
- S = A &B
- C = A ^ B
Full-Adder
- S = A &amp;amp;amp;B& Cin
- Cout = (A^B)&(B^Cin)&(A^Cin)
Ripple Carry Adder
- A chain of full-adders can sum as many bits as needed
- The Cout of each adder is wired to the Cin of the next
- Present the nth bit of inputs A and B to the nth adder
- Set C0 to 0; carry out C4 indicates overflow
- Calculates S = A + B, where Sn is the nth bit of S. . .
- The carry bits ripples across the full adders
- Simplest, but not the fastest (c.f. carry look-ahead)
Representing Negative Numbers
- Sign and Magnitude :What we use in decimal notation: +/− and 0, 1, 2, · · ·, becide the sign bit, other bits are same for a pair of positive and negative number.
- Ones’ Complement : Represent −x by its bitwise inverse (NOT). the bits are revise between positve and negative number, +0 and -0 are special.
- Excess-n :Zero represented by binary n: 02 is thus −n
- Two’s Complement :For an n-bit number, represent −x by 2n − x
Method of Complements :Subtract each digit of x from b − 1, then add 1 to result
Two’s Complements :In base 2 with n bits, represent −x using 2n − x
But there’s a quicker way to calculate 2n − x:
- Take the bitwise inverse (NOT) of x, then add 1 to result
- Addition as for unsigned numbers; just ignore carry bit
- Conventionally we take the MSB to represent the sign 0 for positive, 1 for negative
Thus n bits can represent from −2n−1 up to 2n−1 − 1
All modern processors primarily use two’s complement
lecture 7
Sign Extension :For a signed byte, copy the MSB (bit 7) 24 times:
lb and lh performs sign extension;
However, add and addi also check for overflow
Overflow when result exceeds −231 _ x <>On overflow, trigger an error exception Try
- li $t0, 0x7fffffff
- addi $t0, $t0, 1
- Checking for Overflow
- addu $s0, $s1, $s2
- xor $t0, $s1, $s2
- blt $t0, $zero, no overflow
- xor $t0, $s0, $s1
- bge $t0, $zero, no overflow
- # we have overflow!
- no overflow: # rest of program
Multiplication Product of m- and n-digit numbers requires m + n digits
n-Bit Binary Multiplication
Slow compared to e.g. addition; takes many cycles Would stall the next instructions in the pipeline Independent unit (from main ALU) for muln and divn Source operands come from the usual register file Results written to two special registers HI and LO
lecture 8
Shifting the Point What is 0.110 in binary? 0.110 = 0.0001001001 . . .2 Digits repeat forever – no exact finite representation!
Use binary scaling: e.g.
- let one increment represent 1/16th Hence,
- 0000.00012 = 1 _= 1/16 = 0.0625
- 0001.10002 = 24 _= 24/16 = 1.5 Fixed Point Arithmetic
Fixed position for binary point Addition same as integers: a/c + b/c = (a + b)/c
Multiplication mostly unchanged, but must scale after
a b
- * - =(a × b)/c
c c
e.g. 1.5 × 2.5 = 3.75
0001.10002 × 0010.10002 = 0011.1100 00002
Scientific Notation
- General form ±m × be where
- The mantissa contains a decimal point
- The exponent is an integer e 2 Z
- The base can be any positive integer b 2 N_
- A number is normalised when 1 _ m < 0016 =" 0" 6=" 0" ff16 =" 0" 6=" 0"> largest representable number
- Alternative is to give a wrong value, or raise an exception
- Overflow gives ±1 (underflow gives denormalised)
- In long computations, only a few results may be wrong
- Raising exceptions would abort entire process
- Giving a misleading result is just plain dangerous
- Infinities and NaN propagate through calculations, e.g. 1 + (1 ÷ 0) = 1 +1 = 1 ; (0 ÷ 0) + 1 = NaN + 1 = NaN
lecture 9
Floating Point Addition
- Suppose f0 = m0 × 2e0 and f1 = m1 × 2e1
- Then f0 × f1 = m0 × m1 × 2e0+e1
- Shift the smaller number right until exponents match
- Add/subtract the mantissas, depending on sign
- Normalise the sum by adjusting exponent
- Check for overflow
- Round to available bits
- Result may need further normalisation; if so, goto step 3
- 1 Add the exponents (be careful, excess-n encoding!)
- 2 Multiply the mantissas, setting the sign of the product
- 3 Normalise the product by adjusting exponent
- 4 Check for overflow
- 5 Round to available bits
- 6 Result may need further normalisation; if so, goto step 3
IEEE 754 Rounding
Hardware needs two extra bits (round, guard) for rounding
IEEE 754 defines four rounding modes
- Round Up Always toward +1 Round Down Always toward −1 Towards Zero Round
- down if positive, up if negative
- Round to Even Rounds to nearest even value: in a tie, pick the closest ‘even’ number: e.g. 1.5 rounds to 2.0, but 4.5 rounds to 4.0
Here be Dragons
Cannot rely on e.g. (a + b) + c = a + (b + c)
e.g. calculate 1 + 1020 − 1020 on a computer
Absolute and Relative Error
- We wish to represent some given some number m
- Its IEEE 754 representation is n – an approximation
- The absolute error is defined to be
- a = |m − n|
- The relative error is defined as
- r = |m − n|/n
- m The true value of n lies within the ranges
- n ± a = [n − a, n + a], or
- n(1 ± r ) = [n(1 − r ), n(1 + r )]
Error Propagation
- Addition or subtraction sums absolute error of operands (x ± ax ) + (y ± ay ) = (x + y) ± (ax + ay )
- When x _ −y, the error can be as large as the result
- Multiplication or division sums relative error of operands : x(1 ± rx ) × y(1 ± ry ) = (x × y)(1 ± (rx + ry ) ± rx*ry ) We can ignore the much smaller rx*ry term
Example: given the relative error of x, y and z,
- what is the absolute error in the expression y2 − 4xz?
- y2(1 ± 2ry ) − 4xz(1 ± (rx + rz )) = (y2 − 4xz) ± (2y2ry + 4xz(rx + rz ))
Monday, 23 April 2007
square_root
Square Root Approximation Library
Successive Approximation Algorithm
Successive approximation is an iterative algorithm for approximating the square root of a number. The algorithm is based on the following observations:
If x is the square root of N then,
(1) (N/x) = x so
(2) (x + (N/x)) / 2 = x.
It can be shown that if y is an approximation of the square root of N then,
(3) (y + (N/y)) / 2 is a better approximation.
Using equation (3) repeatedly allows an approximation for the square root of N to be continuously refined. The refinement of the approximation may be stopped once the difference between successive approximations is less than some threshold.
Bisection Algorithm
Bisection is another iterative process used to approximate the square root of number. The algorithm works by repeatedly reducing the range of values which the square root of a value is known to exist in. Given an initial value N and an approximate square root guess of x, the bisection algorithm is implemented using the following steps:
Step 1. Set the square root upper bound to N.
Step 2. Set the square root lower bound to 1.*
Step 3. If (x)2 is close enough to N, x is the square root. Exit.
Step 4a. If (x)2 <> N, set the upper bound to x, and let x be half way between the lower bound and the old x.
Step 5. Go to Step 3.
*NOTE: For N between 0 and 1, set the lower bound to 0 and the upper bound to 1
other reference:
Ancient Square Roots
Square root
example_Structure
College Application Essays Help Lesson Three: Example Essay Structures
which is quite good, it gives some points and support a real example.
How Do I Write an Example/Illustration Essay?
illustrate the general structure including what every parts should be.
mips_arithmetic
CHAPTER 8 — Binary Addition and Two's Complement
Here are some details:
usually the operands and the result have a fixed number of bits (usually 8, 16, 32, or 64). These are the sizes that processors use to represent integers.
1. to keep the result the same size as the operands, you may have to include zero bits in some of the leftmost columns.
2. compute the carry-out of the leftmost column, but don't write it as part of the answer (because there is no room if you have a fixed number of bits.)
3. when the operands are represented using the unsigned binary scheme (the base two representation scheme discussed in the last two chapters) a carry-out of 1 from the leftmost column means the sum does not fit into the fixed number of bits. This is called Overflow.
4. when the operands are represented using the two's complement scheme (which will be described at the end of this chapter), then a carry-out of 1 from the leftmost column is not necessarily overflow.
Overflow Detection
The electronic circuits of a computer can easily detect overflow by checking if the carry-out of the leftmost column is a zero or a one. A program might branch to an error handling routine when overflow is detected.
when the "Binary Addition Algorithm" is used with unsigned binary integer representation:The result is CORRECT only if the CARRY OUT of the high order column is ZERO.
Sign-Magnitude Representation
It uses one bit (usually the leftmost) to indicate the sign. "0" indicates a positive integer, and "1" indicates a negative integer. The rest of the bits are used for the magnitude of the number
One pattern corresponds to "minus zero", 1000 0000. Another corresponds to "plus zero", 0000 0000.
This is what is wrong with Roman Numerals: they can represent any positive integer you want, but they are very, very poor when used in computation.
Two's Complement
Start with an N-bit representation of an integer.
To calculate the N-bit representation of the negative integer:
1. Reflect each bit of the bit pattern (change 0 to 1, and 1 to 0).
2. Add one.
here is what is going on: When each bit of a pattern is reflected then the two patterns added together make all 1's.
adding one to this pattern creates a pattern of all zero's:
Three patterns added together result in a zero. If one pattern represents an integer, then the sum of the other two patterns represents the negative of the integer.
pattern + pattern reflected + one = all zeros
pattern + (pattern reflected + one ) = all zeros
pattern + (two's complement of pattern) = all zeros
it looks like +128 and - 128 are represented by the same pattern. This is not good. A non-zero integer and its negative can't both be represented by the same pattern. So +128 can not be represented in eight bits. The maximum positive integer that can be represented in eight bits is 12710. The negative integers -1 .. -12710 also can be represented.Eight bits can represent the numbers
-12810 ... 0 ... +12710.
it is by happy coincidence that the high order bit of a two's complement integer is 0 for positive and 1 for negative. But, to create the two's complement representation of the negative of a number you must "reflect, add one".
to convert N bits of two's complement representation into decimal representation:
1. If the integer is negative, complement it to get a positive integer.
2. Convert (positive) integer to decimal (as usual).
3. If the integer was originally negative, put "-" in front of the decimal representation.
with two's complement representation the result of addition is correct if the carry into the high order column is the same as the carry out of the high order column. The carry can be one or zero. Overflow is detected by comparing two bits, an easy thing to do with electronics
CHAPTER 9 — First SPIM Program
1. Register Display: This shows the contents (bit patterns in hex) of all 32 general purpose registers, the floating point registers, and a few others.
2. Text Display: This shows the assembly language program source, the machine instructions (bit patterns in hex) they correspond to, and the addresses of their memory locations.
3. Data and Stack Display: This shows the sections of MIPS memory that hold ordinary data and data which has been pushed onto a stack.
4. SPIM Messages: This shows messages from the simulator (often error messages).
Text is the name for machine language bit patterns intended for eventual execution. The word "program" is often ambiguous, so "text" is used. "Text" is a machine language program waiting to become part of an executing process.
Character output from the simulated computer is in the SPIM console window, shown as an icon in the picture.
.text is a directive. A directive is a statement that tells the assembler something about what the programmer wants, but does not itself result in any machine instructions. This directive tells the assembler that the following lines are ".text" -- source code for the program.
.globl main is another directive. It says that the identifier main will be used outside of this source file (that is, used "globally") as the label of a particular location in main memory.
The line main: defines a symbolic address (sometimes called a statement label). A symbolic address is a symbol (an identifier) that is the source code name for a location in memory. In this program, main stands for the address of the first machine instruction (which turns out to be 0x00400000). Using a symbolic address is much easier than using a numerical address. With a symbolic address, the programmer refers to memory locations by name and lets the assembler figure out the numerical address.
CHAPTER 10 — A MIPS Programming Model
Memory Model
modern computer systems nearly always use cache and virtual. But our abstract view of memory does not include them. The purpose of virtual memory is to make it appear as if a program has the full address space available. So our programming model has the full address space. The purpose of cache is to transparently speed up memory access. So our programming model does not include cache. Memory in the programming model is as follows:
data:
MIPS memory is an array of 232 bytes. Each byte has a 32-bit address. Each byte can hold an 8-bit pattern, one of the 256 possible 8-bit patterns. The addresses of MIPS main memory range from 0x00000000 to 0xFFFFFFFF.
However, user programs and data are restricted to the first 231 bytes. The last half of the address space is used for the operating system and for specialized purposes.
operation:
The processor chip contains registers, which are electronic components that can store bit patterns. The processor interacts with memory by moving bit patterns between memory and its registers.
• Load: a bit pattern starting at a designated address in memory is copied into a register inside the processor.
• Store: a bit pattern is copied from a processor register to memory at a designated address.
Bit patterns are copied between the memory and the processor in groups of one, two, four, or eight contiguous bytes. When several bytes of memory are used in an operation, only the address of the first byte of the group is specified.
Memory Layout
though the address space is 32 bits, the top addresses from 0x80000000 to 0xFFFFFFFF are not available to user programs. They are used for the operating system and for ROM. When a MIPS chip is used in an embedded controller the control program exists in ROM in this upper half of the address space.
The parts of address space accessible to a user program are divided as follows:
Text Segment: Thisholds the machine language of the user program (the text).
Data Segment: This holds the data that the program operates on. Part of the data is static. This is data that is allocated by the assembler and whose size does not change as a program executes. Values in it do change; "static" means the size in bytes does not change during execution. On top of the static data is the dynamic data. This is data that is allocated and deallocated as the program executes. In "C" dynamic allocation and deallocation is done with malloc() and free().
Stack Segment: At the top of user address space is the stack. With high level languages, local variables and parameters are pushed and popped on the stack as procedures are activated and deactivated.
Registers:
often data consist of several contiguous bytes. Each computer manufacturer has its own idea of what to call groupings larger than a byte. The following is used for MIPS chips.
• byte — eight bits.
• word — four bytes, 32 bits.
• double word — eight bytes, 64 bits.
A block of contiguous memory is referred to by the address of its first byte (ie. the byte with the lowest address.) Most MIPS instructions involve a fixed number of bytes.
Often you need a number of bits other than one of the standard amounts. Use the next largest standard amount, and remember to be careful. Attempting to use the very minimum number of bits is more complicated than it is worth and is a rich source of errors in assembly language programming.
register is a part of the processor that can hold a bit pattern. On the MIPS, a register holds 32 bits. There are many registers in the processor, but only some of them are visible in assembly language. The others are used by the processor in carrying out its operations.
• A load operation copies a bit pattern from memory into a register.
• A store operation copies a bit pattern from a register into memory.
The registers that are visible in assembly language are called general purpose registers and floating point registers. There are 32 general purpose registers. Each general purpose register holds a 32 bit pattern. In assembly language, these registers are named $0, $1, $2, ... , $31. There are 32 floating point registers. These are discussed in a later chapter.
One of the general purpose registers is hard-wired to always contain the value 0x00000000 (all zero bits).
the arithmetic/logic unit (ALU) of a processor performs integer arithmetic and logical operations. For example, one of its operations is to add two 32-bit integers. An integer used as input to an operation is called an operand. One operand for the ALU is always contained in a register. The other operand may be in a register or may be part of the machine instruction itself. The result of the operation is put into a general purpose register.
Machine instructions that use the ALU specify four things:
As execution proceeds through a list of instructions, a special register, the program counter, points at the instruction that is next in line to execute.
Fetch the next Instruction. The program counter contains the address of the next machine instruction. The instruction is fetched from memory.
Increment the PC. The address in the program counter is incremented by four.
Execute the Instruction. The machine operation specified by the instruction is performed.
CHAPTER 11 — Immediate Operands and Bitwise Logic
General OR Immediate Instruction
here is a description of the ori instruction used as a bitwise OR instruction:
ori d,s,const # register d <-- bitwise OR of const
# with the contents of register $s
# const is 16-bits, so
# 0x0000 ... const ... 0xFFFF
The parts of the instruction must appear in the correct order, and const must be within the specified range. If the immediate operand in the assembly language shows less than 16 bits (as does 0x2 in the previous example) then the assembler expands it to the required sixteen bits. If the assembly language specifies more than sixteen bits, then the assembler writes an error
message.
CHAPTER 12 — Shift Instructions and Logic Instructions
Shifting in Place
hen an ALU operation is performed: (1) data is copied from the register(s) into the ALU. Then (2), the ALU does the operation. Next (3) the result is written to the designated result register. There is no problem when an operand register is also the result register because the operand data was transferred to the ALU in the first step, leaving the register open to receive the result.
No-Op
A machine instruction that does nothing is called (in official computer science jargon) a no-op. The no operation instruction is surprisingly useful, especially for MIPS.
CHAPTER 14 — Integer Multiplication, Division and Arithmetic Shift Instructions
he product of two N-place decimal integers may need 2N places. This is true for numbers expressed in any base. In particular, the product of two integers expressed with N-bit binary may need 2N bits.
MIPS Multiply Unit
he multiply unit of MIPS contains two 32-bit registers called hi and lo. These are not general purpose registers. When two 32-bit operands are multiplied, hi and lo hold the 64 bits of the result. Bits 32 through 63 are in hi and bits 0 through 31 are in lo.
mult s,t # hilo <-- $s * $t. two's comp operands multu s,t # hilo <-- $s * $t. unsigned operands add and addu perform the same operation. The "u" means "don't trap overflow". With mult and multu, different operations are carried out. Neither instruction ever causes a trap.
The significant bits in a positive or unsigned number represented in binary are the most significant 1 bit (the leftmost 1 bit) and all bits to the right of it. For example, the following has 23 significant bits: 0000 0000 0100 0011 0101 0110 1101 1110
The significant bits in a negative number represented in two's complement are the most significant 0 bit (the leftmost 0 bit) and all bits to the right of it. For example, the following has 23 significant bits: 1111 1111 1011 1100 1010 1001 0010 0010
To ensure that a product has no more than 32 significant bits, ensure that the sum of the number of significant bits in each operand is 32 or less. For the programming in this course you will not need to be careful about this.
The mfhi and mflo Instructions
here are two instructions that move the result of a multiplication into a general purpose register: mfhi d # d <-- hi. Move From Hi mflo d # d <-- lo. Move From Lo The hi and lo registers cannot be used with any of the other arithmetic or logic instructions. If you want to do something with a product, it must first be moved to a general purpose register. However there is a further complication on MIPS hardware:
Rule: Do not use a multiply or a divide instruction within two instructions after mflo or mfhi. The reason for this involves the way the MIPS pipeline works. On the SPIM simulator this rule does not matter.
The div and the divu Instructions
ith N-digit integer division there are two results, an N-digit quotient and an N-digit remainder. With 32-bit operands there will be (in general) two 32-bit results. MIPS uses the hi and lo registers for the results:
The sra Instruction
Sometimes you need to divide by two. This instruction is faster and more convenient than the div instruction.
CHAPTER 15 — Memory Access Instructions
he operands for all arithmetic and logic operations are contained in registers. To operate on data in main memory, the data is first copied into registers. A load operation copies data from main memory into a register. A store operation copies data from a register into main memory .
When a word (4-bytes) is loaded or stored the memory address must be a multiple of four. This is called an alignment restriction. Addresses that are a multiple of four are called word aligned. This restriction makes the hardware simpler and faster.
Big Endian and Little Endian
load word or store word instruction uses only one memory address. The lowest address of the four bytes is used for the address of a block of four contiguous bytes.
Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory.
Little Endian Byte Order: The least significant byte (the "little end") of the data is placed at the byte with the lowest address. The rest of the data is placed in order in the next three bytes in memory.
Intel 80x86: little-endian.
Macintosh: big-endian.
MIPS Addresses
An instruction that refers to memory uses a base register and an offset. The base register is a general purpose register that contains a 32-bit address. The offset is a 16-bit signed integer contained in the instruction. The sum of the address in the base register with the (sign-extended) offset forms the memory address.
CHAPTER 16 — More Memory Access
CHAPTER 29 — Binary Fractions
Limited Precision
The important point of all this is that on the number line from zero to 15.9375 not all real numbers can be represented. This is called a limit in precision. Floating point representation has the same problem.
Converting Representation from Decimal to Binary
To convert a decimal fraction to Base 2: Repeatedly multiply the decimal fraction by two. After each multiplication, copy the bit (0 or 1) that moves into the one's place (the place just left of the radix point) to the right of the binary fraction, then erase it from the decimal fraction. Stop when the decimal fraction is zero. (Note: if this never happens, stop when you have enough bits in the binary fraction.)
CHAPTER 30 — IEEE 754 Floating Point
Scientific Notation
10+n means move the decimal point n places right.
10-n means move the decimal point n places left.
IEEE 754 Floating Point
Bits 0 through 22 are for the mantissa; bits 23 through 30 are for the exponent; and bit 31 is the sign bit. The mantissa and exponent fields work like the similar parts in scientific notation (details follow). The sign bit gives the sign of the entire expression: a 0 bit means positive and a 1 bit means negative.
Very tricky: The mantissa represents the 23-bit binary fraction part of a 24-bit number that starts with a "1". The 20 place (the one's place) is presumed to contain a 1 and is not present in the mantissa. This trick gives us 24 bits of precision with only 23 bits.
The Exponent
The exponent is expressed using a biased integer. The true exponent is added to +12710 resulting in an unsigned binary integer. The biased integer is encoded using 8-bit unsigned binary.
A biased exponent of +127 represents the actual exponent 0.
A biased exponent of +128 represents the actual exponent 1.
A biased exponent of +126 represents the actual exponent -1.
Exceptions: (1) A floating point value of 0.0 is represented with a mantissa of 23 zero bits and an exponent of 8 zero bits. It is not legal to have an exponent of zero with a non-zero mantissa. (2) The exponent 25510 (1111 1111) is used to signal various problems, such as division by zero.
Float Formula
ere is a formula that summarizes the past several pages. In it, s is the sign bit (0 or 1), M is the mantissa (000...000 to 1111...111) and E is the biased exponent. value = (-1)s × 1.M × 2E-127
To convert a paper-and-pencil number into IEEE floating point, fill in each piece of the picture. Let us represent 1.0 as a 32-bit IEEE 754 float.
CHAPTER 31 — Floating Point Arithmetic on MIPS
MIPS Floating Point
Floating point on MIPS was originally done in a separate chip called coprocessor 1 (also called the FPA for Floating Point Accelerator). Modern MIPS chips include floating point operations on the main processor chip. But the instructions sometimes act as if there were still a separate chip.
MIPS has 32 single precision (32 bit) floating point registers.
The registers are named $f0 – $f31
$f0 is not special (it can hold any bit pattern, not just zero).
Single precision floating point load, store, arithmetic, and other instructions work with these registers.
Because floating point zero has the same representation as integer zero, 32 zero-bits. Register $0 works as a floating point zero as well as an integer zero.
Double Precision
MIPS also has hardware for double precision (64 bit) floating point operations. For this, it uses pairs of single precision registers to hold operands. There are 16 pairs, named $f0, $f2, — $f30. Only the even numbered register is specified in a double precision instruction; the odd numbered register of the pair is included automatically.
Some MIPS processors allow only even-numbered registers ($f0, $f2,...) for single precision instructions. However SPIM allows all 32 registers in single precision instructions. These notes follow that usage.
Full-Word Aligned
However, if you want to perform floating point arithmetic, then the floating point number must be in a floating point register
Floating Point Services
To print a floating point value to the SPIM monitor, use service 2 (for single precision) or service 3 (for double precision). To read a floating point value from the user, use service 6 (for single precision) or service 7 (for double precision). These notes deal mostly with single precision.
Compilers that keep track of the data types of values and that make sure that the correct types are used as arguments do strong type checking. Java is strongly typed. In assembly language type checking is largely absent.
Data Movement
CHAPTER 32 — Floating Point Comparison Instructions
Comparison Instructions
Testing if two floating point numbers are exactly equal is sometimes NOT a good idea. Floating point calculations are not exact. Sometimes values are not equal even though mathematically they should be. It is best to use "less than" or "less than or equal" instead of testing for exact equality. Here are some MIPS comparison instructions for single precision floating point:
Branch Instructions
The floating point branch instructions inspect the condition bit in the coprocessor. The bc1t instruction takes the branch if the bit is true (==1). The bc1f instruction takes the branch if the bit is false (==0). These are the only two floating point branch instructions.
The branch instructions have a one instruction branch delay. Hardware requires a nop instruction after each branch instruction. For this chapter, let us not bother with this. When running the programs with SPIM, disable branch delays in the settings menu
Newton's Method
Newton's method is a common way to compute the square root of a number. Say that n is the number and that x is an approximation to the square root of n. Then: x' =(1/2)(x + n/x)
x' is an even better approximation to the square root. The reasons for this are buried in your calculus book (which you, perhaps, have buried in the darkest corner of your basement). But, to make the formula plausible, look what happens if the approximation x happens to be exactly the square root. In other words, what if x = n0.5. Then: x' = (1/2)(x + n/x) = (1/2)( n0.5 + n/n0.5 )
= (1/2)(n0.5 + n0.5) = n0.5
If x gets the exact value, it stays fixed at that value.
Ending Test
But, due to the lack of precision with floating point, the best we can hope for is to calculate an x such that: 0.999999 <>The left and the right bound in the above have 6 decimal digits of precision. If 1.00000 is subtracted from this value the result is: -0.000001 <>To be safe, terminate the loop when: n/x*x - 1 <>
Sunday, 22 April 2007
closer
lyric:
I've had enough, of this parade.
I'm thinking of, the words to say.
We open up, unfinished parts,
Broken up, its so mellow.
And when I see you then I know it will be next to me
And when I need you then I know you will be there with me
Ill never leave you...
Just need to get closer, closer,
Lean on me now,
Lean on me now,
closer, closer,
Lean on me now,
Lean on me now.
Keep waking up (waking up), without you here (without you here).
Another day (another day), another year (another year).
I seek the truth (seek the truth), we set apart (we set apart)
Thinking of a second chance (a second chance).
And when I see you then I know it will be next to me
And when I need you then I know you will be there with me
Ill never leave you...
Just need to get closer, closer,
Lean on me now,
Lean on me now,
closer, closer,
Lean on me now,
Lean on me now (lean on me now).
And when I see you then I know it will be next to me
And when I need you then I know you will be there with me
Ill never leave you...
Just need to be closer, closer,
Lean on me now,
Lean on me now,
closer, closer,
Lean on me now,
Lean on me now (lean of me now).
closer, closer... closer, closer.
I ll Be A Virgin I ll Be A Mountain
I ll Be A Virgin I ll Be A Mountain
all linked lyric and his official web
Snow White
And I lied in your arms
You dreamed of all our children
Playing in the sun
I hope, I hope that you're alright
No More Lies To Reach You
No more lies around
I tried hard to see you
I tried hard to sound
No more lies to sound
I tried hard to see you
And I tried hard to sound
No more vows around
I tried hard to fool you
And hard to lose the ground
No more vows to sound
I tried hard to fool you
And hard to lose the ground
No more lies in my head
Your Stammering Kisses
In a room of empty walls?
With your vacant stare
And gloomy thoughts of sorrow?
Flown to America?
Oh, but all that I recall
Your stammering kisses is all that I need
Your stammering kisses is all that I have
Your stammering kisses is all that I'll get
Did you break your wings in a rage?
Are you flying now
And still it feels like falling?
Flown to America?
Oh, but all that I recall
Velvet Son
As you fought all the sounds in me
At the time of escapades up in the mountains
The sound of the bells embraced me
As you taught all the kids to shoot
At the time of escapades down in the valley
You fired a velvet gun
My warehouse legs, my Arabian chimes
Should I leave them by your gun?
Or, long-faced Lady, should I run?
And to dive in your open sea
At the time of escapades out in the desert
You cradled our velvet son
Silly Lily, Funny Bunny
Head over heels built up house
I scream and I lean in vain tonight
Remember the words that I said
As you're silly, Lily
I keep on knocking at your door with my head
As you're funny, bunny
Tasting like drops of cold rain
I'll drink and I'll drown and ruin the whole world
So think of the words that I said
I'll Be A Virgin, I'll Be A Mountain
My love is growing
My dreams have ended
And my soul is stranded
I'll swim to you
I'll leave my prison
To swim to you
When I reach you
I'll be a mountain
When I touch you
Wilted Flower
Were sumptuous rainfalls
Dreary whispering of how you love
Sun-baked objects
And I still hear your withered talk
I am blooming
Without you
You're a wilted flower
How could I now miss your face
As I'm watered in a shower?
And I still hear your withered talking
Messed-up Girl
Staying up all night and losing our pearl?
Why are you lying?
Why are you sighing, my love?
Your cheeks are all red
It's hard for you to hide that you betrayed me in his bed
But still you don't leave me
Still you don't leave, oh my love
What keeps you from falling prey to his charms?
Is it your love?
Oh, do you still love me, my dear?
But I'll be your moon
Brightening your night, but fading too soon
Brightening your path with my borrowed light, oh my love
Silver lining
Noble sweetness
Always shining
How can you do this?
Oh, how can you do this to me?
Staying up all night and losing our pearl?
Why are you lying?
Why are you sighing, my love?
The Saviour
And ruin my kingdom
Force me to break down
Take my pride
Plunder my homeland
Leave me down on the ground
And abduct my brothers
Pilfer my treasures
Waste my fields
That's what I deserve
For redeeming all mournful souls
With my splendour
I'll shine until I fall
I'll shine until I fall, my father
I'll shine until I fall
There's nothing in the world to save my life
You Came To Me When I Was Born
You came to me when I was torn
You came to me when I was strung out
You came to me when I was born
You came to me when I was mad
You came to me when I was lying
You came to me when I was sad
You came to me when I was passed
You came to me when I was longing
You came to me when I was lost
You came to me when I was caught
You came to me when I was crying
You came to me when I was fought
Feel Like Children
My heart is quiet
No tomorrow
No more sorrow
This winter's night
Heals my wounds
Stops my everlasting sighs
But I am yours
Together we could
Together we could
Fall asleep
And drift away
Cry in peace
Feel like children
Grey
I lose my daydreamsI lose my colours
I lose my longing
I find myself
CEP_Essay
question:
Question 4: How successfully can fiscal policy be used to combat (a) recessions and (b) 'overheating' in the economy? Use examples and evidence to support your arguments.
- Offer clear and concise definitions in the introduction ( Fiscal Policy, recession, overheating, business cycle etc)
- Discuss how fiscal policy operates and its types
- Discuss its affect on AD/AS
- Discuss the effectiveness and limitations of fiscal policy
- Illustrate the above with specific evidence
Please through the following articles and the relevant chapters in your textbook before you think about constructing an essay plan.
Survey: The unfinished recession The Economist.
Why
Interest rates: what the economists say: Thursday February 8, 2007
Guardian Unlimited
http://business.guardian.co.uk/story/0,,2008562,00.html
Notes
总需求:
(PE_p729)经济波动的基本模型:
短期经济模型集中在两个变量上:
- 用实际GDP衡量的经济物品和劳务产量
- 用CPI或GDP平减指数衡量的物价总水平
(P508)实际GDP回答了一个假设的问题,如果我们已过去某一年的价格来评价物品和劳务,今年生产的物品与劳务的价值是多少 。 实际GDP说明了经济的整体物品与劳务生产的变动。实际GDP是按照不变的价格衡量的物品与劳务的生产。 总之, 名义GDP使用当年的价格来评价经济中的物品与劳务的生产的价值。 实际 GDP是用不变的基年价格来评价经济中物品与劳务生产的 价值 。他反映了经济满足人们需要与欲望的能力。衡量了经济福利。
GDP平减指数:反映了物品与劳务的价格, 不反映生产量。等于名义GDP/实际GDP
总需求和总供给模型(model of aggreatedemand and aggreate supply):
- 总需求曲线(aggregate-demand curve):表示在每一种物价水平时,家庭,企业和政府想购买的物品和劳务总量。
- 总供给曲线(aggregate-supply curve):表示在每一种物价水平时,企业生产并销售的物品与劳务的总量。
为什么总需求曲线向右下方倾斜:
GDP:Y=C+I+G+NX
假设政府支出由政策决定,则其他三部分的组成取决于经济状况,特别是取决于物价水平。这里的假设也就是说总货币量的供给在一段时间内是相同的。
- 物价水平与消费:财富效应。钱包与银行账户上所持有的货币的名义值是固定的,但实际值不固定。当物价水平下降时,美元更值钱,可以买到更多的物品和劳务。 物价水平下降时消费者更富裕,鼓励他们更多的支出,消费支出增加意味着物品与劳务的需求更大。
- 物价水平与投资:利率效应。(第30章)提到,物价水平是货币需求量的一个决定因素。物价水平低,则购买相同物品和劳务所需要持有的货币就少,就有更多面额的货币转化成了有利息的资产。银行业就有了将以前更充分的资金作为贷款,所以利率会下降,而降低的利率又促进了借款。所以较低的物价水平降低了利率,鼓励了更多的支出与投资物品,从而增加了物品和劳务的需求量。
- 物价水平与净出口:汇率效应。物价水平低会带来利率低,,于是更多的投资转向国外市场?????????,于是增加了外汇市场上本国货币的供给。,从而使本国货币相对于其他通货而贬值。 外国物品相对于国内物品就变得昂贵了。这种实际汇率(国内与国外物品的相对价格) 的变动,减少了进口,所以净出口增加。所以,当美国物价水平下降引起美国利率下降,实际汇率贬值,刺激了美国的进出口,从而增加了物品与劳务的总需求。
- 消费引起的移动:任何一个改变人们的一种物价水平时想消费多少的时间都会使总需求曲线移动。例如,股市上涨,税收水平。减税时候,鼓励人们更多的支出,总需求曲线向右移动,反之亦然。
- 投资引起的移动:投资税收优惠(减免与企业的投资支出相关的税收)增加企业在利率为一定时需求的投资数量,所以投资税收优惠是总需求曲线向右移动。短期中货币供给增加会降低利率,抑制投资。 许多经济学家认为,整个美国历史上的货币政策的变动是总需求移动的一个重要来源。
- 政府购买引起的移动:驱策这移动总需求曲线的最之间的方法是政府购买。直接增加总需求的量的多少。
- 净出口引起的移动:
- 短期中,总需求移动引起经济中物品与劳务产量的波动。
- 长期中,总需求移动影响物价总水平,但不影响总产量。
(PE-747)2001年的衰退,三大冲击,网络泡沫,恐怖袭击和财务丑闻。在总统的要求下,国会在2001年通过了减税法案,包括直接的退税。减税的一个亩苗就是吃几消费者的支出,在恐怖主义者袭击之后,国会增加了从简纽约的资金和帮组有困难的民航业的政府支出。这些财政政策的目的就是是总需求曲线的向右移动,抵消经济经历的三次紧缩性的冲击。美联储叶通过实施扩张性的货币政策来帮组合扩大总需求。货币增长加速,利率下降。
总供给移动的影响:
总共给曲线的移动会引起stagflation-衰退(产量减少)和通货膨胀(物价上涨)的结合那些能影响总需求的决策者不能同时抵消着两种不利的影响,通常是抵消总供给曲线的移动,将其维持在自然产量率上,因为,他们允许用成本增加来影响长期物价水平。
总需求和总共给的来源:凯恩斯的《就业,利息和货币通论》。主要观点,衰退和萧条之所以会发生,是因为对物品与劳务的总需求不足。
difinition of fiscal police in wiki_pedia http://en.wikipedia.org/wiki/Fiscal_policy:
Fiscal policy is the economic term that defines the set of principles and decisions of a government in setting the level of public expenditure and how that expenditure is funded. Fiscal policy and monetary policy are the macroeconomic tools that governments have at their disposal to manage the economy. Fiscal policy is the deliberate and thought out change in government spending, government borrowing or taxes to stimulate or slow down the economy, also known as the contractionary policy. It contrasts with monetary policy, which describes the policies about the supply of money to the economy.
Fiscal policy is described as being either neutral, expansionary, or contractionary. An expansionary fiscal policy occurs when the government lowers taxes and increases spending; thus expanding output (national income). An increase in government spending or a cut in taxes shifts the aggregate demand curve to the right. An expansionary fiscal policy will expand the economy's growth. A contractionary fiscal policy occurs when the government raises taxes and lowers spending; thus lowering output (national income). A decrease in government purchases or an increase in taxes shifts the aggregate demand curve to the left. A contractionary fiscal policy will constrict the economy's growth.
(PE_p765) 财政如何影响中需求:
财政政策是指政府对政府购买或税收总水平的选择(PE_765)。财政政策主要影响物品与劳务的总需求。
政府购买的变动:政府改变其物品与劳务的购买,可以直接是总需求曲线移动。
乘数效应:政府购买,增加了企业的就业和利润,随着工人收入增加和企业所有者的利润增加,促进了对消费品的支出。同时也促进的别的企业的需求。所以政府支出的每一美元可以在全社会所带动增加的物品与劳务的总需求大于一美元。所以叫multiplier effect。这种产生于消费支出反映的乘数效应由于投资对更高水平需求的反应而得到了加强。在这种情况下,较高的政府需求刺激了较高的投资品需求。这种来自于投资需求的正的反馈有时候被称为投资加速器。乘数=1/(1-x)。 乘数的大小取决于边际消费倾向。因为更高的收入会引起更大的消费支出。
挤出效应:当政府购买增加了物品与劳务的总需求时,利率也会随之升高,较高的利率会减少投资支出,阻止总需求增加。称为crowding-out effect。 企业的收入增加,家庭计划购买更多的物品与劳务,于是选择更多的以流动形势持有自己的财富。也就是说财政扩张的收入增加提高了货币需求。由于货币供给的垂直曲线是固定的。 为了保持货币供应平衡,利率必然会上升????????????。利率上升减少了物品与劳务的需求量。,特别是对住房和企业投资品的需求减少了。 也就是说,当政府购买增加提高了物品与劳务的需求时,他也会挤出投资。从而影响了社会的总需求。
总之,当物品与劳务总需求的增加与政府购买的需求, 取决于乘数效应和挤出效应的强弱。
税收变动:
税收变动:
减税增加了消费,使总需求曲线向右移动。
税收变动引起的总需求移动的幅度也受乘数和挤出效应的影响。所以总需求曲线的移动可以大于或小于引起他的税收变动。
还有一个重要因素巨鼎税收引起的总需求移动幅度:家庭对税收变动的持久的还是暂时的感觉。
大多数经济学家认为,财政政策的短期宏观经济效应主要是通过总需求发生作用的。但财政政策也会潜在的影响物品与劳务的供给量。一些供给学派经济学家认为,减税的影响如此之大,以致降低税率实际将通过提高工人努力程度来增加税收收入。政府购买变动也会潜在的影响总供给,例如政府投资公路建设,则可以提高企业的作业效率。但这种投资更趋向于是一种长期的投资。
运用政策来稳定经济:
政府要尽量避免成为经济波动的原因。凯恩斯强调在总需求看来不足以维持充分就业水平的生产时,政府应该积极的刺激总需求。
消费信心指数?????
财政政策也有相当大的时滞,主要是由于政治过程。在美国,大多数政府支出与税收的变动必须经过参众两院的国会委员会,等等,完成过程需要几个月,甚至是几年。到财政政策的变动通过并实施时,经济状况可能已经改变了。
原因是因为经济预测既不稳定。但是衰退和萧条实际上是在没有任何预兆的情况下发生的。最好的决策者也只能在衰退和萧条发生的时候对经济变动做出变动。
为了避免了时滞,automatic stabilizers 是在经济景如衰退使决策者不用采取有益的行动就可以刺激总需求的财政政策变动。其中最重要的是税制度,根据情况收扩税收。 政府支出也可以作稳定器。特别是在社会福利这一方面
经济萧条和经济过热的定义
在一些年份,并没有出现正常的经济增长。企业无法把他们提供的所有物品与劳务都卖出去,因此,他们削减生产,解雇工人,失业增加,而且工厂被限制,由于经济生产的物品和劳务少了,实际GDP和其他的收入指标下降。 如果这种收入减少和失业增加较为缓和, 这种时期就被称为衰退,如果较为严重,就称为萧条(depression)。
经济波动的三个事实:
- 经济波动是无规律的和无法预测的。
- 大多数宏观经济数量同时波动。
- 随着产量减少,失业增加。
The main reading for this lecture is: Mankiw: Chapters 33 & 34
Additional reading:
-Begg and Ward : Chapter 11
- BFD: chapter 19 " Introduction to macroeconomics", chapter 20 "Output
and aggregate demand" and chapter 21 "Fiscal policy and foreign trade",
- Griffiths & Wall: chapters 16 - 19.
- Parkin, Powell & Matthews: chapters 21 - 24.
- Sloman: chapter 17.
Friday, 20 April 2007
regular_expression
- * metacharacter means any srtings of zero or more characters, eg *.*,
- ? matches any single character
- [] matches any of the eclosed charcter. [a-z] or [!abc]
- ` substitutes the output of a command.
Avoiding Shell Expansion: The character needs to be quoted or escaped
quoted:
- "" everything between " and " is taken literally, except for : $ ` ' " .
- '' everything between ' and ' is taken literally except for ' . we can embed another ' within a pare of ' using escaping.
Escaped: using \
- The character following a backslash \ is taken literally.
- Use \ within ″ ″ or ’ ’ to escape ″, $, and ′ when necessary.
p11
shell_script
- [zliybsj2@unnc-cslinux ~]$ echo $PATH
- /usr/kerberos/bin:/usr/local/bin:
- /bin:/usr/bin:/usr/X11R6/bin:/opt/SUNWappserver/jdk/bin/:
- /usr/NX/bin:/home/domain/zliybsj2/bi
- [zliybsj2@unnc-cslinux ~]$ echo $TERM
- xterm
- [zliybsj2@unnc-cslinux ~]$ echo $HOME
- /home/domain/zliybsj2
- [zliybsj2@unnc-cslinux ~]$ echo $PS1
- [\u@\h \W]\$
- using all capitals,
- using echo to get the value of a variable.
- variables are expanded by the shell before he command is executed.
- environment variables can be used by any program.
- variables change is only visible in the current shell.child process don't automatically inherit the environmrnt variables from their parent. using export to let proecessed get the changed value, eg export VAR=value, then $VAR in child process is value, or stay same. using : to add somthing to PATH, eg, export PATH=$PATH:new stuff
PATH:
- it tells UNIX where to look for executables
- when you type the name of a program, the shell will look for it in your PATH
- ecah directory seperated by a colon
- changed PATH can only live in current widow.
shell script:
- the shell is a command interpreter
- shell script is a text file contains all command you want to group, which is executed in a sub shell.
- first line is a specially comment: #!/bin/sh tell program which kind of shell will be using to execut this shell.
chomd :
- chmod o-r coursework
- chmod u+x shellscript
- chmod a+x shellscript
- chmod +x directory
input and output:
- echo works like Java's println.
- argument: $0, $1, $2,...... $#
conditionals:
- if ...
- then ...
- else if ...
- else ...
- fi
read: to get input to interacte with users
can have more than one argument. will bind the first word of input to the first variable and bind the rest to the second. this acts like a list or array, so can be used with for.
controlling input:
- using <<>
- using <>