第六章:常用类 的认识

第六章:常用类

主要内容:

字符串相关类(StringStringBuffer)、基本数据类型包装类、Math类、File类、枚举类

1.string

Java.lang.String类代表不可变的字符序列。

String类常见的构造方法:

String(String original)

创建一个String对象为original的拷贝

String(char[] value)

用一个字符数组创建一个String对象

String(char[] valueint offset, int count)

用一个字符数组从offset项开始的count个字符序列创建一个String对象

 

例子:

public class Test1 {

    public static void main(String[] args){

        String s1 = "hello";

        String s2 = "world";

        String s3 = "hello";

        System.out.println(s1 ==s3 ); //ture

 

        s1 = new String("hello");

        s2 = new String("hello");

        System.out.println(s1 ==s2 );//false

        System.out.println(s1.equals(s2) );//ture

 

        char [] c = {'s', 'u', 'n', '1', 'j', 'a', 'v', 'a'};

        String s4 = new String(c);

        String s5 = new String(c,4,4);

        System.out.println(s4 );//sun1java

        System.out.println(s5 );//java

    }

}

 

2. string类常用的方法:

Public char charAt(int index)

返回字符串中第index个字符。

Public int length()

返回字符串的长度

Public int indexof ( String str)

返回字符串中出现str的第一个位置

Public int indexof ( String strint fromIndex)

返回字符串中从fromIndex开始出现str的第一个位置

Public boolean equalsIgnoreCase(String another)

比较字符串与another是否一样(忽略大小写)

Public String replace (char oldChar, char newchar)

在字符串中用newchar 字符替换oldchar字符

Public boolean startswith(String prefix)

判断字符串是否以prefix字符串开头

Public boolean endsWith(String suffix)

判断字符串是否以prefix字符串结尾

Public String toUpperCase()

返回一个字符串为该字符串的大写形式

Public String toLowerCase()

返回一个字符串为该字符的小写形式

Public String substring(int beginIndex)

返回该字符串从beginIndex开始到结尾的字符串

Public String substring(int beginIndexint endIndex)

返回该字符串从beginIndex开始到endIndex结尾的子字符串

Public String trim()

返回将该字符串去掉开头和结尾空格后的字符串

 

Public static String valueOf(基本数据类型)方法,可以将基本数据类型转换为字符串类型

 

编写程序输出一个字符串中的大写英文字母数,小写英文字母数以及非英文字母数的个数,如下:

public class TestString {

    public static void main(String[] args) {

      String s = "AaaaABBBBcc&^%adfsfdCCOOkk99876 _haHA";//输出大小写的个数和其他字符的个数

       int lCount = 0, uCount = 0, oCount = 0;

 

       for(int i=0; i<s.length(); i++) {

                     char c = s.charAt(i);

                     if(c >= 'a' && c <= 'z') {

                            lCount ++;

                     } else if (c >='A' && c <= 'Z') {

                            uCount ++;

                     } else {

                            oCount ++;

                     }

              }

 

        System.out.println(lCount + " " + uCount + " " + oCount);

    }

//15 12 10

 

编写程序写一个方法,输出在一个字符串中,指定字符串出现的次数,如下:

public class TestString {

    public static void main(String[] args) {

String s = "sunjavahpjavaokjavajjavahahajavajavagoodjava";//含多少个java字符串

 

        String sToFind = "java";

        int count = 0;

        int index = -1;

 

        while((index = s.indexOf(sToFind)) != -1) {

            s = s.substring(index + sToFind.length());

            count ++;

        }

 

        System.out.println(count);

 

}

}

//7

 

3.StringBuffer

Java.lang. StringBuffer代表可变的字符序列

例子:

 

public class TeststingBuffer {

    public static void main(String[] args){

        String s = "Mircosoft";

        char[]a = {'a','b','c'};

        StringBuffer sb1 = new StringBuffer(s);

        sb1.append('/').append("IBM").append('/').append("Sun");//sb1.append添加字符串序列

        System.out.println(sb1);

        StringBuffer sb2 = new StringBuffer("数字");//StringBuffer添加字符串序列

        for(int i=0;i<=9;i++){

            sb2.append(i);

        }

        System.out.println(sb2);

        sb2.delete(8,sb2.length()).insert(0,a); //删除8开始到sb2.length()的一段字符序列,添加0位置a的所有字符串

        System.out.println(sb2);

        System.out.println(sb2.reverse()); //sb2.reverse将字符串逆序

 

    }

}

//Mircosoft/IBM/Sun

//数字0123456789

// abc数字012345

//543210字数cba

4.基本数据类型包装类

这些包装类封装了一个相应的基本数据类型数值,并为其提供了一系列操作。

 

编译一个方法,返回一个double类型的二维数组,数组的元素通过解析字符参数获得,如字符串参数:

1,23,4,56,7,8

对应数组为:

d[0,0]=1.0  d[0,1]=2.0

d[1,0]=1.0  d[1,1]=4.0  d[1,2]=5.0

d[2,0]=6.0  d[2,1]=7.0  d[2,2]=8.0

 

public class ArrayParser {

    public static void main(String[] args) {

        double[][] d;

        String s = "1,2;3,4,5;6,7,8";

        String[] sFirst = s.split(";"); //根据分号分隔,返回一个字符串数组

        d = new double[sFirst.length][];

        for(int i=0; i<sFirst.length; i++) {

            String[] sSecond = sFirst[i].split(",");//根据逗号分隔,返回一个字符串数组

            d[i] = new double[sSecond.length];

            for(int j=0; j<sSecond.length; j++) {

 

                d[i][j] = Double.parseDouble(sSecond[j]);//将数组解析成double型数据,返回该数据

 

            }

        }

 

        for(int i=0; i<d.length; i++) {

            for(int j=0; j<d[i].length; j++) {

                System.out.print(d[i][j] + " ");

            }

            System.out.println();

        }

    }

}

//

1.0 2.0

3.0 4.0 5.0

6.0 7.0 8.0

 

5.Math

Java.lang.Math提供了一系类静态方法,其返回值一般为double

 Abs绝对值

 Random()返回0.01.0的随机数

Max(double a, double b)比较大

Min(double a, double b)比较小

 

6.File

Java.io.File

创建myfile.txt 并显示其内存大小例子:

 import java.io.*;

public class TestFile {

    public static void main(String[] args) {

        String separator = File.separator;

        String filename = "myfile.txt"; //创建的文件名

        String directory = "mydir1" + separator + "mydir2"; //斜杠的意思

        File f = new File(directory, filename);

        if (f.exists()) {

            System.out.println("文件名:" + f.getAbsolutePath());

            System.out.println("文件大小:" + f.length());

        } else {

            f.getParentFile().mkdirs();

            try {

                f.createNewFile();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}

//文件名:G:\soft\work\spring-web_1\mydir1\mydir2\myfile.txt

//文件大小:0

 

例子:编写程序在命令行中以树壮结构展现特定的文件夹及其子文件(夹)用递归法

import java.io.*;

 

public class FileList {

    public static void main(String[] args) {

        File f = new File("d:/A");

        System.out.println(f.getName());

        tree(f, 1);

    }

 

    private static void tree(File f, int level) {

 

        String preStr = "";

        for(int i=0; i<level; i++) {

            preStr += "    ";

        }

 

        File[] childs = f.listFiles();

        for(int i=0; i<childs.length; i++) {

            System.out.println(preStr + childs[i].getName());

            if(childs[i].isDirectory()) {

                tree(childs[i], level + 1);

            }

        }

    }

 

}

/*A

    B

        E

            F.txt

            H

        F.txt

        G.txt

    C

D.txt

*/

 

7.枚举类

Java.lang.Enum枚举类型

枚举类型:

只能够取特定值中的一个

使用enum关键字

例子:

public class TestEnum {

    public enum MyColor { red, green, blue };//定义一个枚举类型  

    public static void main(String[] args) {

        MyColor m = MyColor.red; //静态变量,指定

        switch(m) {

            case red:

                System.out.println("red");

                break;

            case green:

                System.out.println("green");

                break;

            default:

                System.out.println("default");

        }

        System.out.println(m);

    }

}

//red

//red

 

 

猜你喜欢

转载自h389301776.iteye.com/blog/2198533