Java学习笔记-常用实用类(二)

4 篇文章 0 订阅
2 篇文章 0 订阅

一:StringTokenizer类

此类的对象是用来分解String对象的字符序列的。但与split方法不同的是,它不是使用正则表达式来对字符串进行分解的。
当分析一个String对象的 字符序列并将字符序列分解成可独立使用的单词时,常常用到此类。下面是他的两个构造方法
String Tokenizer(String s)为String对象构造一个分析器,使用默认的分割标记符:空格,换行,回车,Tab符,进纸符来做分隔符。
String Tokenizer(String s,String delim)此方法也是为String对象构造一个分析器,但不同的是,此方法的分隔符为参数delim的字符序列(顺序可以不同,例如:##和##是一样的)

二:Scanner类

1:Scanner对象

Scanner对象可以解析出字符序列中的单词,具体方法为Scanner对象调用useDelimiter(正则表达式)方法来实现。
【注】:
1、Scanner对象调用next方法返回解析到的每一个单词。通过hasNext()方法判断是否将字符串解析完毕。如果解析完成则返回true否则返回false。
2、当字符串中含有数字型单词时,可以利用nextInt(),与nextDouble()方法将其返回。
例如:
Test.java

public class Test{
	public static void main(String args[]){
		String coast="市话76.8元,长途:197.32元,短信:12.68元";
		double priceSum=Getprice.GivePrice(cost);
		System.out.println("%S\n总价:%.2f元\n",cost,priceSum);
		cost="牛奶:8.5元,香蕉3.6元,酱油2.5元";
		priceSum=Getprice.GivePriceSum(cost);
		System.out.pringtln("%S\n总价:%.2f元\n",cost,priceSum);
	}
}

Getprice.java

import java util.*;
public class Getpric{
	public static double GivePriceSum(String cost){
		Scanner scanner=new Scanner(cost);
		Scanner.useDelimiter("[^0123456789.]+");  //设置分隔符
		double sum=0;
		while(scanner.hasNext()){
			try{
				double price=scanner.nextDouble());
				sum+=price;
			}
			catch(InputMismatchExpection exp){
				String t=scanner.next();
			}
		}
		return sum;
	}
} 
		
	

StringTokenizer对象与Scanner对象的区别:
StringTokenizer对象解析单词速度快,占用内存大(解析的单词均被存放到StringTokenizer对象的实体中),就是所谓的空间换速度。而Scanner与其相反,解析单词速度较慢,但是节省内存(之只存放分隔标记符),是以空间换速度。

三:StringBuffer类

1:StringBuffer对象

我们知道对于String对象中的字符序列,一旦确定就不能在对其进行更改了。但对于StringBuffer对象,其长度是可以改变的。
StringBufffer对象可以调用方法append()来实现对字符序列的增加。
例如

StringBuffer s=new StringBuffer("我喜欢");
s.append("打篮球");

那么s对象的字符序列就成了:我喜欢打篮球。
它的三个构造方法:
1、StringBuffer( )
无参数构造方法是创建一个Stringbuffer的对象,分配给可以容纳16个字节的实体,如果内容超过16个字节那么会自动增加哦容量大小。且对象可以通过调用方法length()来获取存放的字符序列的长度。通过方法capacity()来获取当前实体的实际容量大小。
2、StringBuffer(int size)
指定实体容量的大小为size若超出,自动增加。
3、StringBuffer(String s)
指定初始容量为参数s的字符序列长度基础上在加16个。

2:StringBuffer的常用方法

1:append()方法
(1)StringBuffer(String s)
将String对象s的字符序列追加到当前StringBuffer对象字符序列的后面,并返回StringBuffer对象的引用。
(2):StringBuffe(int n)
将int型的参数转换为String对象,追加到当前StringBuffer对象字符序列的后面,并返回StringBuffer对象的引用。
(3):StringBuffer(Object o)
将对象o的字符序列表示追加到当前StringBuffer对象字符序列的后面,并返回StringBuffer对象的引用。
2:public char charAt(int n)以及public void setCharAt(int n,char ch)
charAt(int n)返回字符序列第n个位置的字符。setCharAt(int n,char ch)用参数ch替换字符序列的第n个位置。
3:StringBuffer insert(int idenx ,String str)
对象调用insert方法将str插入到位置为idenx的字符序列中。并返回StringBuffer对象的引用。
4:public StringBuffer reverse()
将当前字符序列翻转,并返回StringBuffer对象的引用。
5:StringBuffer delete(int startIndex,int endIndex)deleteChar(int Index)
从当前字符序列的start位置到end-1为的子字符序列删除。并返回StringBuffer对象的引用。
deleteChar(int Index)则是删除idenx位置的一个字符。
6:StringBuffer replace(int startIndex,int endIndex,cahr ch)
将从start位置到end位置的字符子序列用ch替换。

四:Date类与Calendar类

1:Date类

(1):使用Date类的无参数构造方法可以获得当前本机的日期与时间。例如:

Date date=new Date();
System.out.println(date);

会打印出对应的时间。
(2:):使用带参数的构造方法Date(long time),例如:

Date date=new Date(1000),date2 =new Date(-1000);

参数long time是以毫秒为单位。正数为公元后的时间,负为公元前。

2:calendar类

使用calendar类的static方法getInstance()可以初始化一个日历对象。例如:

Calendar calendar=Calendar.getInstance();

然后,calendar对象就可以调用方法

public final void set(int year,int month,int date)
public final void set(int year,int month,int date,int hour,int minute)
public final void set(int year,int month,int date,int hour,int minute,int second)

例如:
Test.java

package Test;
public class test {
	public static void main(String args[]) {
		CalendarBean cb=new CalendarBean();
		cb.setYear(2022);
		cb.setmonth(10);
		String [] a=cb.getCalendar();
		char [] str="日一二三四五六".toCharArray();
		for(char c:str) {
			System.out.printf("%3c", c);
		}
		for(int i=0;i<a.length;i++) {
			if(i%7==0) {
				System.out.println("");
			}
			System.out.printf("%4s",a[i]);
		}
	}
}

CalendarBean.java

package Test;
import java.util.Calendar;
public class CalendarBean {
	int year=0,month=0;
	public void setYear(int year) {
		this.year=year;
	}
	public void setmonth(int month) {
		this.month=month;
	}
	public String[] getCalendar() {
		String [] a=new String[42];
		Calendar rili=Calendar.getInstance();
		rili.set(year, month-1,1);
		int weekDay=rili.get(Calendar.DAY_OF_WEEK)-1;        //计算一号的星期
		int day=0;
		if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) {
			day=31;
		}
		if(month==4||month==6||month==9||month==11) {
			day=30;
		}
		if(month==2) {
			if(((year%4==0)&&(year%100!=0))||(year%400==0)) {
				day=29;
			}
			else {
				day=28;
			}
		}
		for(int i=0;i<weekDay;i++) {
			a[i]="";
		}
		for(int i=weekDay,n=1;i<weekDay+day;i++){
			a[i]=String.valueOf(n);
			n++;
		}
		for(int i=weekDay+day;i<a.length;i++) {
			a[i]="";
			
		}
		return a;
	}

}

五:Math类、BigInteger类以及Random类

1:Math类

math类中的常用方法:

public static long abs(double a)   //返回一个数的绝对值
public static double max(double a,double b)   //返回较大值
public static double min(double a,double b)
public static double random()    //产生一个0-1之间的随机数(包括0但不包括1)
public static double pow(double a,double b)  //返回a的b次幂
public static double sqrt(double a);   //返回a的平方根
public static double log(double a);   //返回a的对数
public static double sin(double a);  //返回a的sin值
public static double asin(double a);       //返回a的反正弦值
public static double ceil(double a);   //返回大于a的最小整数,并且将改正数转换为double型,ceil(15.2)的值是16.0
public static double floor(double a)    //返回小于a的最大整数
public static long round(double a)   //返回四舍五入后的值(大于0.5入,小于等于0.5谁舍弃)

2:BigInteger类

当需要处理特别大的整数的时候需要用到此类。常用方法如下

public BigInteger add(BigInteger val)   //返回当前对象与val的和
public BigInteger subtract(BigInteger val)  //返回当前对象与val的差
public BigInteger multiply(BigInteger val) //返回当前对象与val的乘积
public BigInteger divide(BigInteger val)  //返回当前对象与val的商
public BigInteger remainder(BigInteger val)  //返回当前对象与val的余
public int compareTo(BigInteger val)   //返回当前对象与val的比较结果大于为1.等于0小于-1
public BigInteger abs();   //返回当前对象的绝对值
public BigInteger pow(int a)   //返回当前对象的a次幂
public String toString()   //返回当前对象的十进制字符串
public String toString(int p)   //返回当前对象的p进制字符串

3:Random类

Random类也可以称为随机数生成器,下面时他的两个常用构造方法

public Random() //根据当前的机器时间创建一个random类
public Random(long seed) //依据种子seed创建

产生一个随机整数:

Random random=new Random();
random.nextInt();             

如果nextInt带参数,生成的随机数小于参数。不能为负数

4:数据的格式化

一:格式化整数
%d、%o、%x、%X
十进制,八进制,小写的十六进制,大写的十六进制。
2:修饰符
“+”正数,“,”按照千分组
3:数据宽度
%md其中m为int型数据表是在整数千有m个空格。
二:格式化浮点数
%f,%e(%E),%g(%G),%a(%A)
十进制浮点数(保留)为有效数字,科学计数法的十进制,

六:Class类与Console类

1:Class类

帮助程序创建其他类的实例,创建对象的方法具体为new运算符,实际上可以使用Class对象得到某个类的实例:
(1):使用Class的类方法得到一个和某类(参数className指定的类)相关的Class

public statuc Class forName(String className)throws classNotFoundException

(2):步骤1中获得的class对象的调用:

public Object newInstance() throws InstanttiationExpection,IllegalAcesssExpection

2:Console类

如果希望在键盘输入一行文本,但不想让此文本回显,即不在命令行显示,可以调用Console类的对象来完成。
需要先使用System类调用console()方法,返回Console类的一个对象,例如:

Console cos=System.console();

然后cos对象调用reafPassword()方法读取在键盘上输入的一行文本,并将文本以一个char数组返回。

char [] password =cos.readPassword;
package Test;
import java.io.Console;
public class test {
	public static void main(String args[]) {
		boolean success=false;
		int count=0;
		Console cons;
		char [] passwd;
		cons=System.console();
		while(true)
		{
			System.out.println("输入密码:");
			passwd=cons.readPassword();
			count++;
			String password=new String(passwd);
			if(password.equals("i love the game"))
			{
				success=true;
				System.out.println("第"+count+"次密码正确");
				break;
			}
			else
			{
				System.out.println("第"+count+"次密码"+password+"不正确");
			}
			if(count==3)
			{
				System.out.println("你"+count+"次密码均不正确");
				System.exit(0);
			}
		}
		if(success)
		{
			System.out.println("你好,欢迎!");
		}
	}
}

七:Pattern类与Matcher类

java中提供的用来进行模式匹配的类。使用步骤如下:
1:建立Patter对象,使用正则表达式作为参数得到一个Patteern类的实例pattern。

Pattern pattern=Pattern.compile(regex);

2:得到Matcher对象,得到可以检索String对象的matcher类的实例。

Matcher matcher=pattern.matcher.(input);

经过上面
两个步骤后,matcher对象就可以调用各种方法对字符序列input进行各种检索了。
具体有以下方法:

public boolean find()  //寻找input和regex匹配的下一字符序列,首次调用,寻找第一个与其匹配的字符序列,若结果为true在调用find继续。
public boolean matches()  //判断input是否和regex完全一致。
public boolean lookingAt()  //判断从起始位置开始是否有与其匹配的子序列,若有可以调用start()和end()方法返回其位置。
public boolean find(int start) //从指定位置start开始判断。
public String replaseAll( String replacements)  //找到匹配的字符序列用replacements代替。
public String replaceFrist(String replacements) //只替换第一个与其匹配的字符序列

八:总结

1:熟练掌握String类的常用方法。
2:掌握String类和StringBuffer类的不同。
3:使用StringTokenizer、Scanner类分析字符序列,获取字符序列中被分割符分割的单词。
4:当程序需要处理时间时,使用Date类和Calendar类。
5:当需要处理特别大数据的时候,可以使用BigInteger类。
6:当需要格式化日期和数据使用String类的static方法format。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值