现在的位置: 首页 > 综合 > 正文

Java集合,IO流,案例加用法

2013年08月10日 ⁄ 综合 ⁄ 共 21573字 ⁄ 字号 评论关闭

集合框架
集合类:
集合就是将若干用途、性质相同或相近的“数据”组合而成一个

整体。
 
 1.列表(List)List集合区分元素的顺序,且允许包含重复元素


 2.集(Set)Set集合中不区分元素的顺序,不允许出现重复元素


 3.映射(Map)映射中保存成对的“键-值”(Key-Value)信息

,映射中不能包含重    复的键,每个键只能映射一个值。
Collcction接口:
public class TestCollcction{
    public static void main(String [] args){
    Collection c=new ArrayList();
    
    c.add("123456");
    c.add("sdfdsf");

    c.remove("123456");//移除
    c.clear();//全部清除
    c.contains("123456");//是否包含“123456”  返回值为

boolean
    c.isEmpty();//是否为空   返回值为boolean
    System.out.println(c);

    Collection c2=new ArrayList();
    c2.add("1234");
    c2.add("45678");

    c.addAll(c2);//把C2的所有的值都添加到C里面
   
    Object[] o=c.toArray();  //toArray 返回值是Object
  for(int i=0;i<o.length;i++){
    syso(o[i]);  //打印数组里所有的元素
  syso(list.get(index));   //得到某一个下标位置的值
   

   Syso(list.indexOf("123"));  //得到下标的位置
   list.remove(3);  //删除下标为3的值
 
}
}
}

Set例子:
 TreeSet集中的值会自动排序,按照升序排列
public class TestSet{
    public static void main(String [] args){

    Set set=new TreeSet();
    set.add("123");
    set.add("456");
    set.add("789");
    

    set.add("");
    System.out.println(set);

        set.add(new Cat("小白",2));
        set.add(new Cat("小花",3));
        set.add(new Cat("小黑",1));
        
        
        System.out.println(set); //把类放到

TreeSet中,会出现异常 ClassCastException 。解//决的办法是

实现Comparable接口 , 这里面有一个compareTo(比较此对象与

指定//对象的顺序)     
}
}
连接↑:
public class Cat implements Comparable
{
    String name;
    int age;
    public Cat(String name,int age){
        this.name=name;
        this.age=age;
        
    }
    @Override
    public int compareTo(Object arg0)
    {
        if(arg0 instanceof Cat){
            Cat c=(Cat)arg0;
            if(this.age>c.age){
                return 1;
                
            }else if(this.age<c.age){
                return -1;
                
            }else{
                //如果年龄相同的话,用字

符串(名字)比
                return

this.name.compareTo(c.name);
            }
            
        }else
        return 0;
    }
    
    public String toString (){
        return name+"     "+age;
        
    }
}

hashset例题:

public class {
 public static void main(String [] args){
   Set set=new HashSet();

    set.add("zhangsan");
    set.add("lisi");
    set.add(null);    //可以加Null值的
    syso(set);//如果里面的值相同,就只能打印一次,所

以说,HashSet里面的值是不相同的   

}
}

list:能重复,也没有顺序的,Set:不能重复,有顺序的

Vector   addElement(这个没有返回值)是同步的,线程安全的,

运行效率要低一些,主要用在线程中。

Stack栈
继承了Vector类,对应数据结构中“后进先出”的规则。
class StackDemo{
   public static void main(String [] args){
    Stack s=new Stack();
    s.add("zhangsan");
    s.add("lisi");
    s.add("wangwu");
    System.out.println(s);
    s.push(".....");//在栈低(最上面)
    s.peek(); //返回值类型 object  取栈低的值,只查看
    s.pop();  //取栈低的值,移除栈

}
}
Iterator接口:
描述的是以统一方式对各种几何元素进行遍历/迭代的工具,也称

“迭代器”。
next() 返回迭代的下一个元素 返回值为boolean
class iterator{
    public static void main(String [] args){
    ArrayList al=new ArrayList();
    al.add("zhangsan");
    al.add("lisi");
    al.add("wangwu");
    
    Iterator it=  al.iterator();//al.iterator 返回值

类型为Iterator
    while(it.hashNext()){
    Syso(it.next());

}
}
}

HashMap与Hashtable
,都是Map的子类,hashMap里面的键-值可以为空的,Hashtable

里面的键-值不可以为空

例子:
public class TestMap{
    public static void main(String [] args){

    Map  map=new HashMap();
    map.put(1,"a");
    map.put(2,"c");
    Syso(map);  //键值可以为空,但是里面的键值不可以

重复不保证其顺序
    map.get(3);//可以根据Key,找到Value

    Map maptable=new HashTable();
    maptable.put(1,"zhangsan");
    maptable.put(2,"lisi");
    syso(maptable);//打印出来的没有顺序,键值不可以为

空都
    }

}

Treemap放入的键也是有顺序的,默认的是升序。也可以指定其他

的排序规则。
public class TreeMapTest{
    public static void main(String []args){
     TreeMap tree=new TreeMap();
    tree.put("a","123");
    tree.put("b","123");
    Syso("tree");//有序排列
    tree.put(new Cat("tom",2),"tom");
    tree.put(new Cat("tom1",1),"tom1");
    syso(tree);
}
}
接上↑
public class Cat implements Comparable
{
    String name;
    int age;
    public Cat(String name,int age){
        this.name=name;
        this.age=age;
        
    }
    @Override
    public int compareTo(Object arg0)
    {
        if(arg0 instanceof Cat){
            Cat c=(Cat)arg0;
            if(this.age>c.age){
                return 1;
                
            }else if(this.age<c.age){
                return -1;
                
            }else{
                //如果年龄相同的话,用字

符串(名字)比
                return

this.name.compareTo(c.name);
            }
            
        }else
        return 0;
    }
    
    public String toString (){
        return name+"     "+age;
        
    }
}

Enumeration接口
作用于Iterator接口类似,但只提供了遍历Vector和Hashtable(

及子类Properties)类型集合元素的功能,且不支持集合元素的

移除操作。

import  java.util.*;
public class TestEnumeration{
    public static void main(String[] args) {
        Vector v = new Vector();
        v.addElement("Lisa");
        v.addElement("Billy");
        v.addElement("Mr Brown");
        Enumeration e = v.elements();
    while(e.hasMoreElements()){
        String value = (String)e.nextElement();
        System.out.println(value);
    }
}

Collections类中定义了多种集合操作方法,实现了对集合元素的

排序、取极值、批量拷贝、集合结构转换、循环移位以及匹配性

检查等功能。
主要方法有:
public static void sort(List list)
public static void reverse(List list)
public static void shuffle(List list)
public static void copy(List dest, List src)
public static ArrayList list(Enumeration e)
public static int frequency(Collection c, Object o)
public static T max(Collection coll)
public static T min(Collection coll)
public static void rotate(List list, int distance)

什么是泛型:
泛型(Gernerics)机制自Java SE5.0开始引入,其实质是将原本确

定不变的数据类型参数化。
泛型好处:
    作为对原有Java类型体系的扩充,使用泛型可以提高

Java 应用程序的类型安全、可维护性和可靠性。
分析:
    集合框架中的数据造型问题。
泛型的用法:
用法:
    创建集合容器时规定其允许保存的元素类s
    型,然后由编译器负责添加元素的类型合法性检查,在

取用集合元素时则不必再进行造型处理。

泛型类
由类型参数修饰的类型称为泛型类
格式:数据类型<类型参数>
泛型类举例:
public class Vector<E> {
public void addElement(E obj) { ---}
public E elementAt(int index) { --- }
}
使用泛型类类时应明确指定类型参数:
    Vector<String> v = new Vector<String>();
定义自己的泛型类(如下):

public class Info<T>{
    T name;
    public void setName(T name){
        this.name=name;
    }
    public T getName(){
        return name;
    }
    public static  void f(Info<String> s){
        Syso("方法一");
    }
    //参数类型是任意的Number类型的子类或者其本身类型    
    public static void f3(Info<? extends Number>  s){
        Syso("方法三");
    }
    //参数类型是任意的String类型的父类或者其本身类型
    public static void f4(Info<? super String> s){
        syso("方法四");
    }
    public static void main(String []args){
    Info<String> i=new Info<String>();
    i.setName("zhangsan");

    }

}

public class TestGernerics{
    public static void main(String [] args){
    ArrayList<String> list=new ArrayList<String>();
    list.add("123");//里面只能是String类型的,不能是

其它类型的
    ArrayList<Cat> list1=new ArrayList<Cat>();
    }
}

同一个泛型类搭配不同的类型参数复合而成的类型属于同一个类

,但却是不同的类型。例如:
Vector<String> 与Vector<Double>
同一个泛型类与不同的类型参数复合而成的类型间并不存在继承

关系,即使是类型参数间存在继承关系时也是如此,例如:
Vector<String>与Vector<Object>

类型通配符“?”
    使用“?”作为类型参数,例如Vector<?>:
Vecot<?>是任何泛型Vector的父类型。
Vector<?>类型的变量在调用方法时是受到限制的——凡是必须知

道具体类型参数才能进行的操作均被禁止。
<修饰符> <类型参数> <返回值类型> <方法名>(形参列表){
….
}

I/O流都属于抽象类

javaIO 编程:
Java I/O原理
基本I/O流类型
I/O应用专题
标准I/O重定向
属性信息导入/导出
随机存取文件
临时文件
对象序列化

基本概念:
I/O(Input/Output)
数据源(Data Source)
数据宿(Data Sink)
Java中把不同的数据源与程序间的数据传输都抽象表述为“流”

(Stream),java.io包中定义了多种I/O流类型实现数据I/O功能

I/O流分类:
输入流(Input Stream) 和输出流(OutputStream)
节点流( Node Stream) 和处理流(Processing Stream)
按照数据流动的方向,Java流可分为输入流( Input Stream)

和输出流( OutputStream)

输入流只能从中读取数据,而不能向其写出数据;
输出流则只能向其写出数据,而不能从中读取数据;

特例:java.io.RandomAccessFile类。
根据数据流所关联的是数据源还是其他数据流,可分为节点流

(Node Stream)和处理流(Processing Stream)

节点流直接连接到数据源
处理流是对一个已存在的流的连接和封装,通过所封装的流的功

能调用实现增强的数据读/写功能,处理流并不直接连到数据源。

按传输数据的“颗粒大小”划分,可分为字符流(Character

Stream)和字节流(ByteStream)
字节流以字节为单位进行数据传输,每次传送一个或多个字节;
字符流以字符为单位进行数据传输,每次传送一个或多个字符。

Java命名惯例:
凡是以InputStream或OutputStream结尾的类型均为字节流,凡是

以Reader或Writer结尾的均为字符流。

抽象类java.io.InputStream是所有字节输入流类型的父类,该类

中定义了以字节为单位读取数据的基本方法,并在其子类中进行

了分化和实现。
三个基本的read方法:
    int read()
    int read(byte[] buffer)
    int read(byte[] buffer, int offset, int length)
其它方法:
    void close()
    int available()
    skip(long n)
    boolean markSupported()

FileInputStream字节流:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestFileStream
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        File file=new File("E:/Niit

0410/Class11/src/org/niit/Gernerics/GernericsTest.java");
        try
        {
            FileInputStream fis=new

FileInputStream(file);
            int a=0;
            int count=0;
            while((a=fis.read())!=-1){
                count++;
                System.out.print((char)a);
            }
            System.out.println("总输出次

数:"+count);
        }
        catch (FileNotFoundException e)
        {    //强异常捕获,若异常抛出
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }try
            {
                //如果使用完后,必须关闭
                fr.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
    }

}

java.io.OutputStream 与java.io.InputStream对应,是所有字

节输出流类型的抽象父类。
三个基本的write方法:
    void write(int c)
    void write(byte[] buffer)
    void write(byte[] buffer, int offset, int length)
其它方法:
    void close()
    void flush()

class TestOutputStream{
    public static void main(String []args){
    FileOutputStream ops=new FileOutputStream

("path");
    ops.write(1223);
    }
}

//文件的复制
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestInputStreamAndOutputStream
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        try
        {
            FileInputStream fis=new

FileInputStream("E:/Niit

0410/Class11/src/org/niit/Gernerics/GernericsTest.java");
            //在当前文件夹下创建一个file.txt

文件进行写入
            FileOutputStream fos=new

FileOutputStream("file.java");
            int i=0;
            while((i=fis.read())!=-1){
                fos.write(i);
            }
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }try
            {
                //如果使用完后,必须关闭
                fr.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }

    }

}

抽象类java.io.Reader是所有字符输入流类型的父类,其中声明

了用于读取字符流的有关方法。
三个基本的read方法:
    int read()
    int read(char[] cbuf)
    int read(char[] cbuf, int offset, int length)
其它方法:
    void close()
    boolean ready()
    skip(long n)
    boolean markSupported()
    void mark(int readAheadLimit)

java.io.Writer与java.io.Reader类对应,是所有字符输出流类

型的共同父类。
五个基本的write方法:
    void write(int c)
    void write(char[] cbuf)
    void write(char[] cbuf, int offset, int length)
    void write(String string)
    void write(String string, int offset, int length)
其它方法:
    void close()
    void flush()

FileInputStream/FileOutputStream
FileInputStream用于读取本地文件中字节数据,

FileOutputStream用于将字节数据写出到文件。
例:使用字节流实现文件复制
    FileReader/FileWriter
    FileReader用于以字符为单位读取文本文件,
    FileWriter类用于将字符数据写出到文本文件中。
例:使用字符流实现文件复制
    BufferedReader/BufferedWriter
    BufferedReader 用于缓冲读取字符,
    BufferedWriter则提供字符的缓冲写出功能

InputStreamReader
InputStreamReader可封装字节输入流并从中读取字节数据,然后

将之转换为字符。
转换时所使用的字符编码可以在构造方法中显式指定,也可以使

用平台的默认字符编码。其
构造方法格式为:
    public InputStreamReader(InputStream in)
    public InputStreamReader(InputStream in, String

enc)
    OutputStreamWriter与InputStreamReader 对应,

OutputStreamWriter可按照特定的字符编码规则

PrintStream
    PrintStream在OutputStream基础之上提供了增强的功能

,即可以方便地输出各种类型数据(而不仅限于byte型)的格式

化表示形式。PrintStream的方法从不抛出IOException。
PrintWriter
    PrintWriter 提供了PrintStream 的所有打印方法,其

方法也从不抛出IOException。
    与PrintStream的区别:作为处理流使用时,

PrintStream只能封装OutputStream类型的字节流,而

PrintWriter既可以封装OutputStream,还能够封装Writer类型字

符输出流并增强其功能。

DataInputStream/DataOutputStream
二者分别实现了DataInput/DataOutput接口
DataInputStream能够以一种与机器无关的方式,直接从底层字节

输入流读取Java基本类型和Sring类型的数据,常用方法包括:
    public DataInputStream(InputStream in)
    public final boolean readBoolean()
    public final byte readByte()
    public final char readChar()
    public final double readDouble()
    public final float readFloat()
    public final int readInt()
    public final long readLong()
    public final short readShort()
    public final String readUTF()
DataOutputStream则能够直接将Java基本类型和String类型数据

写出到其他的字节输出流。

CharArrayReader
    CharArrayReader实现了一个可用作字符输入流的字符缓

冲区。
CharArrayWriter
    CharArrayWriter实现了一个可当作Writer使用的字符输

出缓冲区。
    
标准I/O重定向
    标准输入重定向
    标准输出/标准错误输出重定向
属性信息导入/导出
    属性导出/导入
随机存取文件
    实现文件随机存/取操作
临时文件
    使用临时文件

对象序列化
分析:如何保存数据?
基本概念
    对象的持久性( Object Persistance)
长久保存一个对象的状态并在需要时获取该对象的信息以重新构

造一个状态完全相同的对象。
    对象序列化(Object Serialization)
通过写出对象的状态数据来记录一个对象。
    对象序列化的主要任务
写出对象的状态信息,并遍历该对象对其他对象的引用,递归的

序列化所有被引用到的其他对象,从而建立一个完整的序列化流

实现对象序列化:
要序列化一个对象,其所属的类必须实现以下两种接口之一:
    java.io.Serializable
    java.io.Externalizable
java.io.ObjectOutputStream/ObjectInputStream类分别提供了

对象的序列化和反序列化功能。
用法举例:
    实现对象序列化

*对象序列化过程中的数据保护:
*标记性接口Serializable
在对象序列化过程中,其所属类的static属性和方法代码不会被

序列化处理。
*对于个别不希望被序列化的非static属性,可以在属性声明时使

用transient关键字进行标明。

NIO
*什么是NIO?
*NIO基础
    缓冲区(Buffer)
    通道(Channel)
    字符集转换(Charset)
*高级NIO技术
    子缓冲区和数据共享
    只读缓冲区
    内存映射文件
    文件锁定

//Buffered
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestBuffered
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        try
        {
            FileInputStream fis=new

FileInputStream("E:/Niit

0410/Class11/src/org/niit/Gernerics/GernericsTest.java");
    //BufferedInputStream带有缓冲区
BufferedInputStream bis=new BufferedInputStream(fis);
            int i=0;
            int count=0;
            while((i=fis.read())!=-1){
                count++;
                System.out.print((char)

i);
            }
            System.out.println("共输出

了:"+count+"次");
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }try
            {
                //如果使用完后,必须关闭
                fr.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }

    }

}

//FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestFileReader
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        FileReader fr =null;
        try
        {
            fr = new FileReader("E:/Niit

0410/Class11/src/org/niit/Gernerics/GernericsTest.java");
            int i=0;
            int count=0;
            while((i=fr.read())!=-1){
                count++;
                System.out.print((char)

i);
            }
            System.out.println(count);
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }finally{
            try
            {
                //如果使用完后,必须关闭
                fr.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }
    }

}

//FileWriter
import java.io.FileWriter;
import java.io.IOException;

public class TestFileWriter
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {FileWriter fw=null;
        try
        {
             fw=new FileWriter("shuai.java");
            fw.write("一二三四五六七");
            //flush()刷新,把缓冲区的内容写到

文件中,如果没有的话,close()也可以实现这功能;但是以上

两个都没有的话,那么就不能写入到文件中了
            fw.flush();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }finally{
            
            try
            {//使用完了以后,要关闭
                fw.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }
    }

}

//用Reader和Writh复制文件
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TestReaderAndFileWrith
{

    public static void main(String[] args)
    {    FileReader fr=null;
        FileWriter fw=null;
        try
        {
            fr=new FileReader("E:/Niit

0410/Class11/src/org/niit/Gernerics/GernericsTest.java");
            //true让再次执行,追加到以前的后

面,默认的是False,不追加
            fw=new FileWriter

("Test.java",true);
            
            int a=0;
            while((a=fr.read())!=-1){
                fw.write(a);
                fw.flush();
                
            }
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }finally{
            try
            {
                fw.close();
                fr.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }
        
    }

}

//BufferdReader和BufferedWriter的使用

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TestBufferReader
{
    public static void main(String[] args)
    {
        BufferedReader br=null;
        BufferedWriter bw=null;
        
        try
        {
            bw=new BufferedWriter(new

FileWriter("shuai.txt"));
            br=new BufferedReader(new

FileReader("shuai.txt"));
            String s=null;
            for(int i=0;i<100;i++){
                s= String.valueOf

(Math.random());
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
            
            
            
            while((s=br.readLine())!=null){
                System.out.println(s);
                
            }
            
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }finally{
            try
            {
                bw.close();
                br.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }
    }

}

//InputStreamReader实现小写转换成大写
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestInputStreamReader
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {        //in "标准"输入流  相当于接入到键

盘上
            //而且这个类是不会抛异常的
        InputStreamReader isr=new

InputStreamReader(System.in);
        BufferedReader bf=new BufferedReader

(isr);
        String s=null;
        try
        {
            s=bf.readLine();
            while(s!=null){
                if(s.equalsIgnoreCase

("exit")){
                    break;
                    
                }
                System.out.println

(s.toUpperCase());
                s=bf.readLine();
                
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }finally{
        
            try
            {
                isr.close();
                bf.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }
        
    }

}

//OutputStreamWriter例子
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

public class TestOutputStreamWriter
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        OutputStreamWriter osw = null;
        try
        {
            osw = new OutputStreamWriter(new

FileOutputStream("shuai.txt"));
            osw.write("sss");
            osw.flush();
            System.out.println

(osw.getEncoding());// 打印出系统默认的编码

        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch

block
            e.printStackTrace();
        }
        finally
        {
            try
            {
                osw.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated

catch block
                e.printStackTrace();
            }
        }

    }

}

---------------------------------作业-------------------

-----------------
1.正则表达式判断邮箱是否正确?
class Demo{
    public static void main(String [] args){
        System.out.println("请输入你的邮箱");
        String Email = "^[_.0-9a-z-A-Z-]{5,11}+@

([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$";
        Scanner s=new Scanner(System.in);
        String s1=s.nextLine();
        String s2 = s1;
        Pattern p = Pattern.compile(Email);
        Matcher m = p.matcher(s2);
        boolean res = m.matches();
        if(res==true){
            System.out.println("邮箱地址正确

!");
            
        }else if(res==false){
            System.out.println("邮箱地址错误

!");
        }
}
}
2.求n!?
方法一:不用递归
public class IteratorDemo
{
    public static void main(String[] args)
    {
   int a=1;
     for(int i=1;i<=5;i++){
         a=i*a;
        
     }
     System.out.println(a);

    }
}
方法二:递归
public class IteratorDemo
{
    public static void main(String[] args)
    {
    System.out.println(f(n));
    }
    public int f(int i){
    if(i==1){
        return 1;
         }else{
         return i*f(i-1);
    }

}
}

3.求1,1,2,3,5,8,13.....数列
方法一:递归
public class Test{
      public static void main(String [] args){

       System.out.println(f(n));
}

 public int f(int i){
    if(i==1||i==2){
        return 1;
    }else {
        return f(n-1)+f(n-2)
    }

    }
}
方法二:不用递归
public class Test4
{
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        System.out.println(f(5));

    }
   public static long f(int index){
       if(index==1||index==2){
           return 1;
           
       }   
       long f1=0;
       long f2=1L;
       long f3=1L;
       for(int i=0;i<index-2;i++){
           f1=f2+f3;
           f2=f3;
           f3=f1;           
       }
       return f1;
   }
}

4.坐标的计算

  class Peate
{
    double x,y,z;
    public Peate(double x1,double y1,double z1){
        x=x1;
        y=y1;
        z=z1;
        
    }
    void getX(double x1){
        x=x1;
    }
    void getY(double y1){
        x=y1;
    }
    void getZ(double z1){
        x=z1;
    }
      
    double getText5(Peate p){
        return (x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)+

(z-p.z)*(z-p.z);
        
    }
    }
    public class Test5{
        
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        Peate p=new Peate(50.0,30.0,20.0);
        Peate p1=new Peate(0.0,0.0,0.0);
        System.out.println(p.getText5(p1));
        
    }
    }
5.打印目录下所有的文件
public class Exercise
{
    public static void main(String[] args)
    {
        File f = new File("D:/homework");
        System.out.println("D");
        System.out.println("Workspace");
        getFiles(f,2);
    }

    public static void getFiles(File f, int num)
    {
        String s = "";
        for (int i = 0; i < num; i++)
        {
            s = s + "  ";
        }
        File[] file = f.listFiles();
        if (file != null)
        {
            for (int i = 0; i < file.length;

i++)
            {
                System.out.println

(s+file[i].getName());
                if (file[i].isDirectory

())
                {
                    getFiles(file

[i],num+1);
                }
            }
        }
    }

}

抱歉!评论已关闭.