【笔记】Java——常用类

常用类

1.字符串相关类(String、StringBuffer)
1)String类
  • java.lang.String 类代表不可变的字符序列
(1)String类的常见构造方法
  • String(String original):创建一个String对象为original的拷贝
  • String(char[] value):用一个字符数组创建一个String对象
  • String(char[] value,int offset,int count):用一个字符数组从offset项开始的count个字符序列创建一个String对象
package com.common;
/*
@author qw
@date 2020/8/3 - 20:06
**/
public class Test01 {
    public static void main(String[] args) {
        String s1="hello";
        String s2="world";
        String s3="hello";
        //字符串常量存放在data segment中,只存一份
        //s1创建后在串池中,s3创建时发现已经有"hello",则返回s1的地址,因此相等
        System.out.println(s1==s3);//true

        s1 = new String("hello");
        s2 = new String("hello");
        //使用new关键字创建对象 在堆中分配不同的存储空间,此时比较两者的地址
        System.out.println(s1 == s2);//false
        System.out.println(s1.equals(s2));//true
        //"=="比较两个对象的引用是否相同,"equals()"比较两个对象的值是否相等

        char[] c={'h','i',' ','j','a','v','a'};
        String s4 = new String(c);
        String s5 = new String(c, 3, 4);
        System.out.println(s4);//hi java
        System.out.println(s5);//java
    }
}
(2)String类常用方法①
  • public char chatAt(int index):返回字符串中第index个字符
  • public int length():返回字符串的长度
  • public int indexOf(String str):返回字符串中出现str的第一个位置
  • public int indextOf(String str,int fromIndex):返回字符串中从fromIndex开始出现str的第一个位置
  • public boolean equalsIgnoreCase(String another):比较字符串与another是否一样(忽略大小写)
  • public String replace(char oldChar,char newChar):在字符串中用newChar字符替换oldChar字符
package com.common;
/*
@author qw
@date 2020/8/3 - 21:15
**/
public class Test02 {
    public static void main(String[] args) {
        String s1="hi java";
        String s2="Hi Java";
        System.out.println(s1.charAt(1));//i
        System.out.println(s2.length());//7
        System.out.println(s1.indexOf("java"));//3
        System.out.println(s1.indexOf("Java"));//-1
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equalsIgnoreCase(s2));//true

        String s="我是程序员,我在学java";
        String str = s.replace('我', '你');
        System.out.println(str);//你是程序员,你在学java
    }
}
(3)String类常用方法②
  • 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 beginIndex,int endIndex):返回该字符串从beginIndex开始到endIndex结尾的子字符串
  • public String trim():返回将该字符串去掉开头和结尾空格后的字符串
package com.common;
/*
@author qw
@date 2020/8/3 - 21:28
**/
public class Test03 {
    public static void main(String[] args) {
        String s="Welcome to Java World!";
        String s1=" hi java ";
        System.out.println(s.startsWith("Welcome"));//true
        System.out.println(s.endsWith("World"));//false
        System.out.println(s.toLowerCase());//welcome to java world!
        System.out.println(s.toUpperCase());//WELCOME TO JAVA WORLD!
        System.out.println(s.substring(11));//Java World!
        System.out.println(s1.trim());//hi java
    }
}
(4)String类常用方法③

静态重载方法

  • public static String valueOf(…)可以将基本类型数据转换为字符串:
    • public static String valueOf(double d)
    • public static String valueOf(int i)
  • 方法public String[] split(String regex)可以将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
package com.common;
/*
@author qw
@date 2020/8/3 - 21:35
**/
public class Test04 {
    public static void main(String[] args) {
        int j=1234567;
        String num=String.valueOf(j);
        System.out.println("j是" + num.length() + "位数");//j是7位数
        String s="XieFeiJi,M,2007";
        String[] sPlit=s.split(",");
        for (int i = 0; i < sPlit.length; i++) {
            System.out.println(sPlit[i]);
        }
        /*
        XieFeiJi
        M
        2007
         */
    }
}

(5)String类练习
package com.common;
/*
@author qw
@date 2020/8/3 - 21:55
**/

/**
 * 编写一个程序,输出一个字符串中的大写英文字母数
 * 小写英文字母数以及非英文字母数
 */
public class Ex01 {
    public static void main(String[] args) {
        String s = "ahcyAlfnSLO^$@(*&8961YJ";
        int uCount=0;//大写字母个数
        int lCount=0;//小写字母个数
        int oCount=0;//其他
        //法①
        /*
        for (int i = 0; i <s.length() ; i++) {
            char ch=s.charAt(i);
            if(ch>='a' && ch<='z'){
                lCount++;
            } else if (ch >= 'A' && ch <= 'Z') {
                uCount++;
            }else{
                oCount++;
            }
        }
         */

        //法② 使用String类中的方法
        String sL = "abcdefghijklmnopqrstuvwxyz";
        String sU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i <s.length() ; i++) {
            char ch=s.charAt(i);
            if (sL.indexOf(ch) != -1) {
                lCount++;
            } else if (sU.indexOf(ch) != -1) {
                uCount++;
            } else {
                oCount++;
            }
        }
    }
}
package com.common;
/*
@author qw
@date 2020/8/3 - 21:56
**/

/**
 * 编写一个方法,输出在一个字符串中
 * 指定字符串出现的次数
 */
public class Ex02 {
    public static void main(String[] args) {
        String s="hijavajavaaaokkkjjjavajhhhhgoodjava";
        String sToFind="java";
        int count=0;//计数
        int index=-1;//indexOf(str)中当str不存在返回-1

        while ((index = s.indexOf(sToFind)) != -1) {
            s = s.substring(index + sToFind.length());
            //从sToFind返回的位置index,+上其自身的长度==>即下标向后移的位数
            //从新的位置开始到结尾 再判断是否含有sToFind字符串
            count++;
        }
        System.out.println(count);
    }
}
2)StringBuffer类
  • java.lang.StringBuffer代表可变的字符序列

  • StringBuffer和String类似,但StringBuffer可以对其字符串进行改变

(1)StringBuffer的常见构造方法
  • StringBuffer():创建一个不包含字符序列的"空"的StringBuffer对象
  • StringBuffer(String str):创建一个StringBuffer对象,包含与String对象str相同的字符序列
(2)StringBuffer常用方法①
  • 重载方法 public StringBuffer append(…) :可以为该StringBuffer对象添加字符序列,返回添加后的该StringBuffer对象引用,例如:
    • public StringBuffer append(String str)
    • public StringBuffer append(StringBuffer sbuf)
    • public StringBuffer append(char[] str)
    • public StringBuffer append(char[] str,int offset,int len)
    • public StringBuffer append(doube d)
    • public StringBuffer append(Object obj)
(3)StringBuffer常用方法②
  • 重载方法 public StringBuffer insert(…) 可以为该StringBuffer对象在指定位置插入字符序列,返回修改后的该StringBuffer对象引用,例如:
    • public StringBuffer insert(int offset,String str)
    • public StringBuffer insert(int offset,double d)
  • 方法 public StringBuffer delete(int start,int end) 可以删除从start开始到end-1为止的一段字符序列,返回修改后的该StringBuffer对象引用
(4)StringBuffer常用方法③
  • 和String类含义类似的方法:
    • public int indexOf(String str)
    • public int indexOf(String str,int fromIndex)
    • public String substring(int start)
    • public String substring(int start,int end)
    • public int length()
  • 方法 public StringBuffer reverse() 用于将字符序列逆序,返回修改后的该StringBuffer对象引用
package com.common;
/*
@author qw
@date 2020/8/4 - 14:13
**/

public class Test05 {
    public static void main(String[] args) {
        String s="Microsoft";
        char[] a = {'a', 'b', 'c'};
        StringBuffer sb1=new StringBuffer(s);
        sb1.append('/').append("IBM").append('/').append("Sun");
        System.out.println(sb1);//Microsoft/IBM/Sun

        StringBuffer sb2 = new StringBuffer("数字");
        for (int i = 0; i <=9 ; i++) {
            sb2.append(i);
        }
        System.out.println(sb2);//数字0123456789
        sb2.delete(8,sb2.length()).insert(0,a);
        System.out.println(sb2);//abc数字012345
        System.out.println(sb2.reverse());//543210字数cba
    }
}

2.基本数据类型包装类
  • 包装类(Integer,Double等)这些类封装了一个相应的基本数据类型数值,并为其提供了一系列操作
  • 以java.lang.Integer类为例,构造方法:
    • Integer(int value)
    • Integer(String s)
1)包装类常见方法
(1)以下方法以java.lang.Integer为例
  • public static final int MAX_VALUE 最大的int型数(2^31 -1)
  • public static final int MIN_VALUE 最小的int型数(-2^31)
  • public long longValue():返回封装数据的long型值
  • public double doubleValue():返回封装数据的double型值
  • public int intValue():返回封装数据的int型值
  • public static int parseInt(String s) throws NumberFormatException:将字符串解析成int型数据,返回该数据
  • public static Integer valueOf(String s) throws NumberFormatException:返回Integer对象,其中封装的整型数据为字符串s所表示
package com.common;
/*
@author qw
@date 2020/8/4 - 16:59
**/

public class Test06 {
    public static void main(String[] args) {
        Integer i = new Integer(100);
        Double d = new Double("123.456");
        int j = i.intValue() + d.intValue();
        float f = i.floatValue() + d.floatValue();
        System.out.println(j);//223
        System.out.println(f);//223.456

        double pi = Double.parseDouble("3.1415926");
        double r = Double.valueOf("2.0").doubleValue();
        double s = pi * r * r;
        System.out.println(s);//12.5663704

        try {
            int k = Integer.parseInt("1.25");//"1.25"不能转为整型 故捕获异常输出
        } catch (NumberFormatException e) {
            System.out.println("数据格式不对!");
        }
        System.out.println(Integer.toBinaryString(123) + "B");//转为二进制:1111011B
        System.out.println(Integer.toHexString(123) + "H");//转为十六进制:7bH
        System.out.println(Integer.toOctalString(123) + "O");//转为八进制:173O
    }
}
(2)练习
package com.common;
/*
@author qw
@date 2020/8/4 - 17:39
**/

import java.util.concurrent.ForkJoinPool;

/**
 * 编写一个方法,返回一个double型二维数组,
 * 数组中的元素通过解析字符串参数获得。
 * 如字符串参数:"1,2;3,4,5,;6,7,8"
 * 对应数组为:
 * d[0,0]=1.0 d[0,1]=2.0
 * d[1,0]=3.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 Test07 {
    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]);
            }
        }

        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();
        }
    }
}


3.Math类
  • java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型
    • abs绝对值
    • sqrt平方根
    • pow(double a,double b)a的b次幂
    • log自然对数
    • exp e为底指数
    • max(double a,double b); min(double a,double b) //ab中的最大;最小值
    • random() 返回0.0到1.0点随机数
    • round() 四舍五入

4.File类
  • java.io.File类代表系统文件名(路径和文件名)
  • File的静态属性String separator 存储了当前系统的路径分隔符
1)File类的常见构造方法
  • public File(String pathname):以pathname为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储
  • public File(String parent,String child):以parent为父路径,child为子路径创建File对象
2)File类常用方法

(1)通过File对象可以访问文件的属性

  • public boolean canRead()//是否可读
  • public boolean canWrite()//是否可写
  • public boolean exists()//是否存在
  • public boolean isDirectory()//是否为目录
  • public boolean isFile()//是否为文件
  • public boolean isHidden()//是否隐藏
  • public long lastModified()//上次修改时间
  • public long length()//文件内容长度
  • public String getName()//获取文件名
  • public String getPath()//获取文件路径

(2)通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)

  • public boolean createNewFile() throws IOException
  • public boolean delete()
  • public boolean mkdir()
  • public boolean mkdirs() //创建在路径中的一系列目录

(3)举例

package com.common;
/*
@author qw
@date 2020/8/4 - 20:09
**/
import java.io.*;

public class Test08 {
    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);// mydir1/mydir2/myfile.txt
        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();
            }
        }
        //文件名:D:\IDEA\Java\mydir1\mydir2\myfile.txt
        //文件大小:0
    }
}

(4)递归列出目录结构

package com.common;
/*
@author qw
@date 2020/8/4 - 20:46
**/

import java.io.*;

public class Test09 {
    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);
            }
        }
    }
}

5.枚举类
  • java.lang.Enum枚举类型
  • 只能够取特定值中的一个
  • 使用enum关键字
package com.common;
/*
@author qw
@date 2020/8/4 - 21:07
**/

public class Test10 {
    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);
    }
}

学习视频——尚学堂马士兵Java视频

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值