您的位置:首页 > 编程语言 > Java开发

八、java常用类

2016-07-02 17:25 405 查看

目录

一、字符串相关类

String类

StringBuffer类

二、基本数据类型包装类

三、Math类

四、File类

五、枚举类

一、字符串相关类

1.String类

java.lang.String代表不可变的字符序列

“xxxx”为该类的一个对象

String类常见的构造方法:

String(String original)//创建一个String对象为original的拷贝
String(char90 value)//用一个字符数组创建一个String对象
String(char[] value,int offset,int count)//用一个字符数组从offset项开始的count个字符序列创建一个String对象


看一个例子:

//测试类
public class Test {
public static void main(String[] args){
String s1 = "hello";
String s2 = "world";
String s3 = "hello";
System.out.println(s1 == s3);
s1 = new String("hello");
s3 = new String("hello");
System.out.println(s1.equals(s3));
System.out.println(s1 == s2);
char c[] = {'s','u','n',' ','j','a','v','a'};
String s4 = new String(c);
String s5 = new String(c,4,4);
System.out.println(s4);
System.out.println(s5);
}
}
//输出结果
//true
//true
//false
//sun java
//java


String类常用方法

public char charAt(int index)
//返回字符串中第index个字符
public int lenth()
//返回字符串长度
public int indexOf(String str)
//返回字符串中出现str的第一个位置
public int indexOf(String str, int fromIndex)
//返回字符串中从fromIndex开始出现str的第一个位置
public boolean equalsIgoreCase(String another)
//比较字符串与another是否一样(忽略大小写)
public String replace(char oldChar,char newChar)
//在字符串中用newChar字符串替换oldChar字符串



public boolean startWith(String prefix)

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

public boolean endsWidth(String suffix)

//判断字符串是否一suffix字符串结尾

public String toUpperCase()

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

public String toLowerCase()

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

public String sunstring(int beginIndex,int endIndex)

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

public String trim()

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


看例子理解:

//测试类
public class Test {
public static void main(String[] args){
String s1 = "sun java";
String s2 = "Sun java";
System.out.println(s1.charAt(1));//u
System.out.println(s2.length());//8
System.out.println(s1.indexOf("java"));//4
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 sr = s.replace('我', '你');
System.out.print(sr);//你是程序员,你在学习java
}
}


//测试类
public class Test {
public static void main(String[] args){
String s = "Welcome to Java World!";
String s1 = "   sun   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());//sun   java
}
}


静态重载方法


public static String valueOf(…)可以将基本数据类型转换为字符串;


例如:


public static String valueOf(double d)

Public static String value of(int i)



方法public Strint[] split(String regex)可以将一个字符串按照指定的分隔符分割,返回分隔后的字符串数组

//测试类
public class Test {
public static void main(String[] args){

int i = 123456;
String sNumber = String.valueOf(i);
System.out.println(“i是”+sNumber.length()+”位数”);
String s = "Nice to meet you";
String[] sPlit = s.split(" ");
for(int k=0;k<sPlit.length;k++){
System.out.println(sPlit[k]);
}
}
}

//输出结果:

//i是7位数//Nice
//to
//meet
//you


2.StringBuffer类

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

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


这里说的可变指的是主要是内存空间,打比方你定义了一个String s1=”a”,s2=”b”如果要执行s1=s1+s2的话,在内存空间中会另外开辟出第三块内存,然后把s1和s2分别附加到第三块内存,再让s1指向第三块内存,完成附加流程。同样的,对于如果你想截取String里的部分字符也要开辟第三块内存空间


StringBuffer类的常见构造方法:

StringBuffer()//创建一个不包含字符序列的“空”的StringBuffer对象
StringBuffer(String str)//创建一个StringBuffer对象,包含与String对象str相同的字符串序列


重载方法

public StringBuffer append(…)可以为该StringBuffer对象添加字符串序列,返回添加后的该StrintBuffer对象引用,例如:


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(double d)

public StringBuffer append(object obj)





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对象引用

和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()用于将字符序列逆序,返回修改后的该S他ringBuffer对象引用

看一个例子:

public class Test {
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");

System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("数字: ");
for(int i=0;i<=9;i++) {
sb2.append(i);
}

System.out.println(sb2);

sb2.delete(8, sb2.length()).insert(0, a);
System.out.println(sb2);

System.out.println(sb2.reverse());
}
}
//输出结果:
//Mircosoft/IBM/Sun
//数字: 0123456789
//abc数字: 0123
//3210 :字数cba


3.练习

//输出指定字符串中大写小写和特殊字符的出现次数
public class Test {
public static void main(String[] args){

String s = "AaaaAbbbbcc+-*adfsfdCCOOkk99876 *haHA";
int big = 0,small = 0, specil = 0;
for(int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if(Character.isLowerCase(c)) {
small++;
}else if (Character.isUpperCase(c)) {
big++;
}else {
specil++;
}
}
System.out.println("小写"+small+"个");
System.out.println("大写"+big+"个");
System.out.println("特殊字符"+specil+"个");
}
}


//输出指定字符串在另一个字符串中出现的次数
public class Test {
public static void main(String[] args){

String s = "sun java sun java sun java sun java ";
String find="java";

int count = 0;
while(s.indexOf(find) != -1) {
s = s.substring(s.indexOf(find) + find.length());
count++;
}
System.out.print(count);
}
}


二、基本数据类型包装类

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

以java.lang.Integer为例;构造方法:

Integer(int value)

Integer(String s)

包装类常见方法:

public static final int MAX_VALUE //最大的int型数(2的31次方-1)
public static final int MIN_VALUE //最小的int型数(-231)
public long longValu() //返回封装数据的long型值
public double doubleValue() //返回封装数据的double型值
public int intVlaue() //返回封装数据的int型值
public static int parseInt(String s) throwsNumberFormatException//将字符串解析成int型数据,并返回值
public static Integer valueOf(String s) shrows NumberFormatException //返回Integer对象,其中封装的整型数据为字符串s所表示


看一个例子:

public class Test {
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);
System.out.println(f);

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

try {
int k = Integer.parseInt("1.25");
} catch(NumberFormatException e ) {
System.out.println("数据格式不对");
}
System.out.println(Integer.toBinaryString(123)+"B");
System.out.println(Integer.toHexString(123)+"H");
System.out.println(Integer.toOctalString(123)+"O");
}
}


public class Test {
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]);
//System.out.println(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();
}
}
}


三、Math类

java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型

常见方法:

abs //绝对值
acos,sin,stan,cos,sin,tan
sqrt //平方根
pow(double a,double b) //a的b次冥
log //自然对数
exp e //底指数
max(double a,double b)
min(double a,doublle b)
random() //返回0.0到1.0的随机数
long round(double a) //double型的数据a转换为long型(四舍五入)
toDegrees(double angrad) //弧度->角度
toRadians(double angdeg) //角度->弧度


看个例子:

public class Test {
public static void main(String[] args){

double a = Math.random();
double b = Math.random();
System.out.println(Math.sqrt(a*a+b*b));
System.out.println(Math.pow(a, 8));
System.out.println(Math.round(b));
System.out.println(Math.log(Math.pow(Math.E,15 )));
double d = 60.0 , r = Math.PI/4;
System.out.println(Math.toRadians(d));
System.out.println(Math.toDegrees(r));

}
}


四、File类

java.io.File类代表系统文件名(路径和文件名)

常见构造方法:

public File(String pathname)//以pathname为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储
public File(String parent,String child)//以parent为父路径,child为子路径创建File对象


File的静态属性String separator存储了当前系统的路径分隔符(windows下是反斜杠,linux下是正斜杠,为了跨平台使用,事实上,在windows上使用正斜杠也是可以的)

常见方法:

//通过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()
//通过file对象创建空文件或目录(在该对象所知的文件或目录不存在的情况下)
public boolean createNewFile() throws IOException
public boolean delete()
public boolean mkdir()
public boolean mkdirs() //创建在路径中的一些列路径


看一个例子:

public class Test {
public static void main(String[] args){

String separator = File.separator;
String filename = "test.txt";
String directory = "testdir1"+separator+"testdir2";
//String directory = "testdir1/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();
}
}
}
}


这个例子里有一个小的注意事项,当找一个类的上层路径,如果这个类是属于某个package下的,那么上层路径应该是这个package的上层路径

//递归列出目录结构
public class Test {
public static void main(String[] args){
File f = new File("F:/java_workspace");
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);
}
}
}
}


五、枚举类

java.lang.Enum枚举类型

只能够取特定值中的一个

使用enum关键字

是java.lang.Enum类型

枚举的意思其实就是事先定义一个范围,让程序在编译的时候就来检查你的变量、对象什么的是不是在这个范围内,而不是在执行的时候才发现

看个例子:

public class Test {

public enum color {red, green, blue};

public static void main(String[] args){
color m = color.red;
switch (m) {
case red:
System.out.println("red");
break;
case green:
System.out.println("green");
break;
default:
System.out.println("default: blue");
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: