字符串实验一Java常用工具类编程

java编程工具  时间:2021-02-26  阅读:()

实验一Java常用工具类编程

§ 1.1实验指导

1、 String类使用

String类表示字符串。 在Java程序中所有的字符串常量如"abc"都被实现为这个类的实例。

1) 、构造函数

String s1="java";

String s2=new String("java") ;

2) 、 比较函数

①==比较引用是否相同if(s1==s2) //返回false

②equals() :比较串内容是否相同if(s1.equals(s2) )//返回true

③compareTo() :比较内容,返回数字s1.compareTo(s2)

如果s1>s2 则返回>0

如果s1=s2 则返回0

如果s1<s2 则返回<0

3) 、取子串substring() ,取字符charAt(index)

String s1="hello java";s1. substring(start,end) ;s1. substring(0,3) ;//start到end-1

String s2=s1. substring(6, 10) ;

4) 、分割split() ;

String s1="c++, java,vb.net";

String[] str=s1. split(", ") ;

String s2="c++. java.vb";

String s2="c++. java.vb dotnet";

String[] str=s2. split("\\. | ") ;for(int i=0; i<str. length; i++)

System.out.println(str[i] ) ;

2、 StringBuffer类

StringBufferpubl ic StringBuffer()

构造一个不包含字符的字符串缓冲区其初始的容量设为16个字符。

StringBufferpubl ic StringBuffer(int length)构造一个不包含字符的字符串缓冲区其初始的容量由参数length设置。

StringBufferpubl ic StringBuffer(String str)构造一个字符串缓冲区来表示和字符串参数相同的字符序列。len gthpubl icint length()返回字符串缓冲区的长度(字符数)。capacitypubl ic int capacity()返回字符串缓冲区的当前容量。 该容量表示可用于插入新的字符的存储空间超出该容量时会发生新的容量分配。ensureCapacitypublic synchronized void ensureCapacity(int minimumCapacity) 保证缓冲区的容量至少等于指定的最小数。 如果字符串缓冲区的当前容量少于该参数 则分配一个新的更大的内部缓冲区。 新容量将取如下参数中较大的一个setLengthpublic synchronized void setLength(int newLength) 设置该字符串缓冲区的长度。 如果参数newLength小于该字符串缓冲区的当前长度。 该字符串缓冲区将被截断来包含恰好等于由参数newLength给出的字符数。a p pe n dpublic synchronized StringBuffer append(Object obj) 把Object型参数的字符串表示添加到该字符串缓冲区。

StringBuffer x=new StringBuffer().append("a").append(4).append("c") .toString();i n se rtpublic synchronized StringBuffer insert(int offset, Object obj) 把Object型参数的字符串表示插入到字符串缓冲区。reversepublic synchronized StringBuffer reverse() 该字符串缓冲区的字符序列被其反向字符序列所替换。toStringpublic String toString() 转换为一个表示该字符串缓冲区数据的字符串。 分配一个新的String对象并且用字符串缓冲区所表示的字符序列进行初始化。 于是此String被返回。 随后缓冲区发生的变化不再影响该String的内容。

3、 日期类示例

1 获取服务器端当前日期import java.util.Date;

Date myDate = new Date() ;

2)获取当前年、 月、 日

Date myDate = new Date() ;int thisYear = myDate.getYear() + 1900;//thisYear = 2009int thisMonth = myDate.getMonth() + 1 ;//thisMonth = 10int thisDate = myDate.getDate() ;//thisDate = 30

3)按本地时区输出当前日期

Date myDate = new Date() ;

out.println(myDate. toLocaleString() ) ;

输出结果为

2003-5-30

4)按照指定格式打印日期import "java.util.Date";import "java. text.DateFormat";

Date dNow = new Date() ;

SimpleDateFormat formatter =new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz") ;

System.out.println("It is " + formatter.format(dNow) ) ;

输出的结果为

It is星期五2003.05.30 at 1 1 :30:46上午CST

5)将字符串转换为日期import="java.util.Date"import="java. text.DateFormat"

String input = "1222-11-11";

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd") ;Date t = null;try{t = formatter.parse(input) ;

System.out.println(t) ;

}catch(ParseException e) {

System.out.println("unparseable using" + formatter) ;

}

输出结果为

Fri Nov 1 1 00:00:00 CST 1222

6)计算日期之间的间隔getTime()函数返回日期与1900-01-0100:00:00相差的毫秒数import="java.util.Date"import="java. text.DateFormat"

String input = "2003-05-01";

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd") ;Date d1 = null;

Date d2 = new Date() ;long diff = d2.getTime() - d1.getTime() ;out.println("Difference is " + (diff/(1000*60*60*24) ) + " days. ") ;输出结果为

Difference is 29 days.

7) 日期的加减运算

方法 用Calendar类的add()方法

Calendar now = Calendar.getInstance() ;

SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at'hh:mm:ss a zzz") ;out.println("It is now " + formatter.format(now.getTime() ) ) ;now.add(Calendar.DAY_OF_YEAR,-(365*2) ) ;out.println("<br>") ;out.println("Two years ago was " + formatter.format(now.getTime() ) ) ;输出结果为

It is now星期五2003.05.30 at 01:45:32下午CST

Two years ago was星期三2001 .05.30 at 01 :45:32下午CST

8)比较日期

方法 用equals()、 before()、 after()方法import="java.util.*"import="java. text.*"

DateFormat df = new SimpleDateFormat("yyy-MM-dd") ;

Date d1 = df.parse("2000-01-01") ;

Date d2 = df.parse("1999-12-31") ;

String relation = null;if(d1. equals(d2) )relation = "the same date as";else if(d1.before(d2) )relation = "before";elserelation = "after";

System.out.println(d1 +" is " + relation + ' ' + d2) ;

输出结果为

Sat Jan 01 00:00:00 CST 2000 is after Fri Dec 31 00:00:00 CST 1999

§ 1.2实验题目

1 、使用类String类的分割spl it将字符串 “Solutions to selected exercises can be foundin the electronic document The Thinking in Java Annotated Solution Guide, avai lablefor a smal l fee from BruceEckel”单词提取输出。单词以空格或,分割。package j ob1;

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

String s1="Solutions to selected exercises " +

"can be found in the electronic document " +

"The Thinking in Java Annotated Solution Guide, " +

"available for a small fee from BruceEckel";

String s2 [ ]=s1.split(" | , ") ;for(int i=0;i<s2.length;i++)

System.out.println(s2 [i] ) ;

}

}

2、设计一个类Student,类的属性有姓名 学号 出生日期性别所在系等。并生成学生类对象数组。按照学生的姓名将学生排序输出。使用String类的compareTo方法。package job1;public class Student {private String name;private int num;private String birth;private String sex;private String sdept;public Student( ) {

}public Student(String name,int num,String birth,String sex,Stringsdepet) {this.name=name;this.num=num;this.birth=birth;this.sex=sex;this.sdept=sdept;

}public String getName( ) {return name;

}public void setName(String name) {

this.name=name;

}public int getNum( ) {return num;

}public void setNum(int num) {this.num=num;

}public String getBirth( ) {return birth;

}public void setBirth(String birth) {this.birth=birth;

}public String getSex( ) {return sex;

}public void setSex(String sex) {this.sex=sex;

}public String getSdept( ) {return sdept;

}public void setSdept(String sdept) {this.sdept=sdept;

}

}package job1;import java.util.Comparator;import java.text.CollationKey;import java.text.Collator;public class MyCmp implements Comparator{public int compare(Object obj1,Object obj2) {

Collator collator=Collator.getInstance( ) ;

CollationKey key1=collator.getCollationKey(obj1.toString( ) ) ;CollationKey key2=collator.getCollationKey(obj2.toString( ) ) ;return key1.compareTo(key2) ;

}

}package job1;import java.util.*;public class TreeText {public static void main(String[ ] args) {

TreeMap map=new TreeMap(new MyCmp( ) ) ;

map.put("蒋高登", "20081851 1990-08-03 男 CS") ;map.put("蒋稀文", "20081852 1989-01-11 男 CS") ;map.put("董骏", "20081850 1990-04-05 男 CS") ;Set keys=map.entrySet( ) ;

Iterator it=keys.iterator( ) ;while(it.hasNext( ) ) {

Map.Entry e=(Map.Entry) it.next( ) ;

System.out.println(e.getKey( )+" "+e.getValue( ) ) ;}

}

}

3、设计一个程序计算2011-05-01 日与系统当前日期相差的天数。package job1 ;import java.text.ParseException;import java.text.SimpleDateFormat;import java.uti l .Date;publ ic class Days{publ ic static void main(String[]args) throws ParseException{

Date d1=new Date();

SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");String s="2011-05-01";

Date d2=format.parse(s);

int days=(int)((d2.getTime()-d 1 .getTime())/(1000*60*60*24));

System.out.print("2011-05-01 日与系统当前时间相差"+days+"天");

}

}

4、使用日历类等相关方法按截图做出一个日历参照书本示例,研究其中代码回顾与复习利用Java Swing编程。

参考 以下函数根据输入的年和月计算相应的数字publ ic void showCalendar(intyear, int month){

Calendar cal=Calendar.getInstance();cal .set(Calendar.YEAR,year);cal .set(Calendar.MONTH,month-1);

//计算当前月一共有多少天int days=cal .getActualMaximum(Calendar.DAY_OF_MONT H);

//计算当前月的1号为星期几cal .set(Calendar.DAY_OF_MONTH, 1);//设置为1号int firstweek=cal .get(Calendar.DAY_OF_WEEK);

。 。 。 。 。

}package job1 ;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.uti l .Calendar;import javax.swing.*;import javax.swing.table.DefaultTableModel ;publ ic class CalendarTable extends JFrame implementsActionListener{private JLabel label_year=new JLabel("年");private JLabel label_month=newJLabel("月");private JComboBox box_year=new JComboBox();private JComboBox box_month=new JComboBox();private JButton btn=new JButton("确定");private JTable table;private String week[]={"日","一","二","三","四","五","六"};private String rows[][]=newString[6][7];

GigsGigsCloud($26/年)KVM-1GB/15G SSD/2TB/洛杉矶机房

GigsGigsCloud新上了洛杉矶机房国际版线路VPS,基于KVM架构,采用SSD硬盘,年付最低26美元起。这是一家成立于2015年的马来西亚主机商,提供VPS主机和独立服务器租用,数据中心包括美国洛杉矶、中国香港、新加坡、马来西亚和日本等。商家VPS主机基于KVM架构,所选均为国内直连或者优化线路,比如洛杉矶机房有CN2 GIA、AS9929或者高防线路等。下面列出这款年付VPS主机配置信息...

npidc:9元/月,cn2线路(不限流量)云服务器,金盾+天机+傲盾防御CC攻击,美国/香港/韩国

npidc全称No Problem Network Co.,Limited(冇問題(香港)科技有限公司,今年4月注册的)正在搞云服务器和独立服务器促销,数据中心有香港、美国、韩国,走CN2+BGP线路无视高峰堵塞,而且不限制流量,支持自定义内存、CPU、硬盘、带宽等,采用金盾+天机+傲盾防御系统拦截CC攻击,非常适合建站等用途。活动链接:https://www.npidc.com/act.html...

新注册NameCheap账户几天后无法登录原因及解决办法

中午的时候有网友联系提到自己前几天看到Namecheap商家开学季促销活动期间有域名促销活动的,于是就信注册NC账户注册域名的。但是今天登录居然无法登录,这个问题比较困恼是不是商家跑路等问题。Namecheap商家跑路的可能性不大,前几天我还在他们家转移域名的。这里简单的记录我帮助他解决如何重新登录Namecheap商家的问题。1、检查邮件让他检查邮件是不是有官方的邮件提示。比如我们新注册账户是需...

java编程工具为你推荐
可以发外链的论坛发外链的论坛哪个比较好,哪个论坛能发外链,能发广告急求。。。。伪装微信地理位置伪装微信地理位置 朋友圈显示地理位置怎么改站长故事爱迪生的故事网站运营网络运营主管的主要工作职责是什么?照片转手绘怎么把图片P成手绘ios系统ios系统有哪些版本?如何快速收录如何掌握百度收录之快速收录微信电话本怎么用微信电话本短信管理功能怎么用?域名库域名赎回期过了多长时间可以注册聚美优品红包聚美优品里怎么合并红包
论坛虚拟主机 winscp site5 博客主机 omnis patcha lamp配置 日本空间 php空间申请 中国电信测速网 免费申请网站 免费智能解析 服务器监测 in域名 全能空间 测速电信 国外免费云空间 买空间网 黑科云 web服务器 更多