第八章学习笔记

 

一,教材学习内容(8常用实用类)

1、String类

1.1 常量对象:构造String常量对象,使用双引号括起的字符序列。String常量被放入常量池中。

常量池:常量池中的数据在运行过程中不允许被改变。

1.2 String对象:构造String对象,使用new运算符首先分配内存空间并在内存空间中放入字符序列。String变量被放入动态池中。

1.3 引用String对象:String常量是对象,因此可以把String常量的引用赋值给一个String对象。

当两个String对象具有同一引用时,他们进行==运算时返回true值,事实上,String对象通过更改引用,可以在运算过程中发生变化。

1.4字符串并置

public class Example8_1 {
  public static void main(String args[]) {
       String hello = "你好";
       String testOne = "你"+"好";             //【代码1】
       System.out.println(hello == testOne);   //输出结果是true
       System.out.println("你好" == testOne);  //输出结果是true
       System.out.println("你好" == hello);    //输出结果是true
       String you = "你";
       String hi = "好";
       String testTwo = you+hi;                //【代码2】
       System.out.println(hello == testTwo);   //输出结果是false
       String testThree = you+hi;                       
       System.out.println(testTwo == testThree); //输出结果是false
    }
}

【代码1】:String testOne = ""+"";的赋值号的右边是两个常量进行并置运算,因此,结果是常量池中的常量"你好"(如果读者学习过编译原理,可能知道所谓的常量优化技术,常量折叠是一种Java编译器使用的优化技术,String testOne = ""+"",被编译器优化为String testOne = "你好",就像int x = 1+2被优化为int x = 3一样),所以 表达式 "你好" == testOne 和表达式

hello == testOne的值都是true

【代码2】:testTwo = you+hi; 的赋值号的右边有变量,例如变量you参与了并置运算,那么you+hi相当于new String("你好"); 因此结果在动态区诞生新对象,testTwo存放着引用BCD5testTwo的实体中存放者字符序列:你好(如图8.4),所以表达式hello == testTwo的结果是false

1.5 String类的常用方法

public int length():获取一个字符串的长度

public boolean equals(String s):判断当前String对象的字符序列是否与参数s指定的String对象的字符序列相同   

public class Example8_2 {
  public static void main(String args[]) {
       String s1,s2;
       s1 = new String("天道酬勤");
       s2 = new String("天道酬勤");
       System.out.println(s1.equals(s2));   	//输出结果是:true
       System.out.println(s1==s2);          	//输出结果是:false
       String s3,s4; 
       s3 = "we are students";
       s4 = new String("we are students");
       System.out.println(s3.equals(s4));   	//输出结果是:true
       System.out.println(s3==s4);         	//输出结果是:false 
       String s5,s6;
       s5 = "勇者无敌";
       s6 = "勇者无敌"; 
       System.out.println(s5.equals(s6));   	//输出结果是:true
       System.out.println(s5==s6);         	//输出结果是:true
    }
}

             

public boolean startsWith(String s):判断当前String对象的字符序列前缀是否是参数指定的String对象s的字符序列

public int compareTo(String s):按字典序与参数s指定的字符序列比较大小。

如果当前String对象的字符序列与s的相同,该方法返回值0,如果大于s的字符序列,该方法返回正值;如果小于s的字符序列,该方法返回负值

public boolean contains(String s):String对象调用contains方法判断当前String对象的字符序列是否包含参数s的字符序列,例如,tom="student",那么tom.contains("stu")的值就是true,而tom.contains("ok")的值是false

public int indexOf (String str):String对象调用方法从当前String对象的字符序列的0索引位置开始检索首次出现str的字符序列的位置,并返回该位置。如果没有检索到,该方法返回的值是–1

public String substring(int startpoint):字符串对象调用该方法获得一个新的String对象,新的String对象的字符序列是复制当前String对象的字符序列中的startpoint位置至最后位置上的字符所得到的字符序列。String对象调用substring(int start ,int end)方法获得一个新的String对象,新的String对象的字符序列是复制当前String对象的字符序列中的start位置至end–1位置上的字符所得到的字符序列。

public String trim() :得到一个新的String对象,这个新的String对象的字符序列是当前String对象的字符序列去掉前后空格后的字符序列

1.6字符串与基本数据的相互转化

使用java.lang包中的Byte、Short、Long、Float、Double类调相应的类方法可以将由"数字"字符组成的字符串,转化为相应的基本数据类型。如:

public static byte parseByte(String s) throws NumberFormatException

public static short parseShort(String s) throws NumberFormatException

public static long parseLong(String s) throws NumberFormatException

public static float parseFloat(String s) throws NumberFormatException

public static double parseDouble(String s) throws NumberFormatException

可以使用String 类的类方法,将基本类型数据转化为字符串类型。

public static String valueOf(byte n)

public static String valueOf(int n)

public static String valueOf(long n) 

public static String valueOf(float n)

public static String valueOf(double n)

1.6 对象的字符串表示

Object类有一个

                 public String toString()

方法,一个对象通过调用该方法可以获得该对象的字符序列表示。一个对象调用toString()方法返回的String对象的字符序列的一般形式为:

public class TV {
   double price ;
   public void setPrice(double m) {
      price = m;
   }
   public String toString() {
      String oldStr = super.toString(); 
      return oldStr+"\n这是电视机,价格是:"+price;
   }
}


import java.util.Date;
public class Example8_5 {
   public static void main(String args[]) {
       Date date = new Date();
       System.out.println(date.toString());
       TV tv = new TV();
       tv.setPrice(5897.98);
       System.out.println(tv.toString());  
   }
}

2、字符串的加密算法

2.1 加密操作

使用一个String对象password的字符序列作为密码对另一个String对象sourceString的字符序列进行加密,操作过程如下。

password的字符序列存放到一个字符数组中,

      char [] p = password.toCharArray();

假设数组p的长度为n,那么就将待加密的sourceString的字符序列按顺序以n个字符为一组(最后一组中的字符个数可小于n),对每一组中的字符用数组a的对应字符做加法运算。比如,某组中的n个字符是a0a1…an-1那么按如下方式得到对该组字符的加密结果:

 

public class EncryptAndDecrypt {   
   String encrypt(String sourceString,String password) { //加密算法
       char [] p= password.toCharArray();
       int n = p.length;
       char [] c = sourceString.toCharArray();
       int m = c.length; 
       for(int k=0;k<m;k++){
            int mima=c[k]+p[k%n];       //加密
            c[k]=(char)mima; 
       }
       return new String(c);    //返回密文
    }
    String decrypt(String sourceString,String password) { //解密算法
       char [] p= password.toCharArray();
       int n = p.length;
       char [] c = sourceString.toCharArray();
       int m = c.length; 
       for(int k=0;k<m;k++){
           int mima=c[k]-p[k%n];       //解密
           c[k]=(char)mima; 
       }
       return new String(c);    //返回明文
   }
}


import java.util.Scanner;
public class Example8_8 {
    public static void main(String args[]) {
       String sourceString = "今晚十点进攻";
       EncryptAndDecrypt person = new EncryptAndDecrypt(); 
       System.out.println("输入密码加密:"+sourceString);
       Scanner scanner = new Scanner(System.in);
       String password = scanner.nextLine();
       String secret = person.encrypt(sourceString,password);
       System.out.println("密文:"+secret);
       System.out.println("输入解密密码");
       password = scanner.nextLine();
       String source = person.decrypt(secret,password);
       System.out.println("明文:"+source);
    }
}

3、正则表达式

3.1 正则表达式:正则表达式是一个String对象的字符序列,该字符序列中含有具有特殊意义字符,这些特殊字符称做正则表达式中的元字符。比如,"\\dcat"中的\\d就是有特殊意义的元字符,代表09中的任何一个,"0cat""1cat""2cat",…,"9cat"都是和正则表达式"\\dcat"匹配的字符序列。

String对象调用public boolean matches(String regex)方法可以判断当前String对象的字符序列是否和参数regex指定的正则表达式匹配

在正则表达式中可以用方括号括起若干个字符来表示一个元字符,该元字符代表方括号中的任何一个字符。例如String regex = "[159]ABC",那么"1ABC""5ABC""9ABC"都是和正则表达式regex匹配的字符序列。例如,[abc]:代表abc中的任何一个;[^abc]:代表除了abc以外的任何字符;[a-zA-Z]:代表英文字母(包括大写和小写)中的任何一个。

3.2 字符串的替换

public String replaceAll(String regex,String replacement)

String对象调用public String replaceAll(String regex,String replacement)方法返回一个新的String对象,这个新的String对象的字符序列是把当前String对象的字符序列中所有和参数regex匹配的子字符序列,用参数replacement的字符序列替换后得到字符序列,例如:

String str ="12hello567bird".replaceAll("[a-zA-Z]+","你好");

那么str的字符序列就是将"12hello567bird"中所有英文字符序列替换为"你好"后得到的字符序列,即str的字符序列是"12你好567你好"

3.3 字符串的分解

public String[] split(String regex)使用参数指定的正则表达式regex做为分隔标记分解出其中的单词,并将分解出的单词存放在字符串数组中。

 例如,对于字符串str :String str = "1949年101日是中华人民共和国成立的日子";

如果准备分解出全部由数字字符组成的单词,就必须用非数字字符串做为分隔标记,因此,可以使用正则表达式:String regex="\\D+";

做为分隔标记分解出str中的单词:String digitWord[]=str.split(regex);

特别地需要特别注意的是,split方法认为分隔标记的左面应该是单词,因此如果和当前String对象的字符序列的前缀和regex 匹配,那么split(String regex)方法分解出的第一个单词是不含任何字符的字符序列(长度为0的字符序列),即""。例如,对于:

String str = "公元1949101日是中华人民共和国成立的日子";

使用正则表达式String regex="\\D+"作为分隔标记分解str的字符序列中的单词:

String digitWord[]=str.split(regex);

那么,数组digitWord的长度是4,不是3digitWord[0]digitWord[1]digitWord[2]digitWord[3]分别是:"""1949""10"和"1"。

4、StringTokenizer类

4.1 StringTokenizer对象称作一个字符串分析器可以使用下列方法:

1) nextToken():逐个获取字符串中的语言符号(单词),字符串分析器中的负责计数的变量的值就自动减一  。

2) hasMoreTokens():只要字符串中还有语言符号,即计数变量的值大于0,该方法就返回true,否则返回false。

3)countTokens()得到分析器中计数变量的值。

import java.util.*;
public class PriceToken {
    public double getPriceSum(String shoppingReceipt) { 
       String regex = "[^0123456789.]+"; //匹配非数字字符序列
       shoppingReceipt = shoppingReceipt.replaceAll(regex,"#");
       //replaceAll方法见8.1.6节的例子10
       StringTokenizer fenxi = new StringTokenizer(shoppingReceipt,"#");
       double sum = 0;
       while(fenxi.hasMoreTokens()) {
           String item = fenxi.nextToken();
           double price = Double.parseDouble(item);
           sum = sum + price;
       }   
       return sum;
    }
    public double getAverPrice(String shoppingReceipt){
        double priceSum = getPriceSum(shoppingReceipt);
        int goodsAmount = getGoodsAmount(shoppingReceipt); 
        return priceSum/goodsAmount;
    }
    public int getGoodsAmount(String shoppingReceipt) {
       String regex = "[^0123456789.]+"; //匹配非数字字符序列
       shoppingReceipt = shoppingReceipt.replaceAll(regex,"#");
       StringTokenizer fenxi = new StringTokenizer(shoppingReceipt,"#");
       int amount = fenxi.countTokens();
       return amount;
    }
}

public class Example8_12  { 
   public static void main(String args[]) {
      String shoppingReceipt = "牛奶:8.5圆,香蕉3.6圆,酱油:2.8圆";
      PriceToken lookPriceMess = new PriceToken();
      System.out.println(shoppingReceipt);
      double sum =lookPriceMess.getPriceSum(shoppingReceipt);
      System.out.printf("购物总价格%-7.2f",sum);
      int amount = lookPriceMess.getGoodsAmount(shoppingReceipt);
      double aver = lookPriceMess.getAverPrice(shoppingReceipt);
      System.out.printf("\n商品数目:%d,平均价格:%-7.2f",amount,aver);
    } 
}

5、Scanner类

5.1 Scanner类解析字符串:

Scanner对象可以解析字符序列中的单词,例如,对于String对象NBA

String NBA = "I Love This Game";

为了解析出NBA的字符序列中的单词,可以如下构造一个Scanner对象。

Scanner scanner = new Scanner(NBA);

5.2  scanner将空格做为分隔标记来解析字符序列中的单词,具体解析操作:

scanner调用next()方法依次返回NBA中的单词,如果NBA最后一个单词已被next()方法返回,scanner调用hasNext()将返回false,否则返回true

对于被解析的字符序列中的数字型的单词,比如618168.98等,scanner可以用nextInt()nextDouble()方法来代替next()方法,即scanner可以调用nextInt()nextDouble()方法将数字型单词转化为intdouble数据返回。

如果单词不是数字型单词,scanner调用nextInt()nextDouble()方法将发生InputMismatchException异常,在处理异常时可以调用next()方法返回该非数字化单词。

6、StringBuffer类

6.1 什么是StringBuffer类?

String对象的字符序列是不可修改的,也就是说,String对象的字符序列的字符不能被修改、删除,即String对象的实体是不可以再发生变化的,StringBuffer类的对象的实体的内存空间可以自动地改变大小,便于存放一个可变的字符序列。比如,对于:StringBuffer s = new StringBuffer("我喜欢");对象s可调用append方法追加一个字符序列,s.append("玩篮球")。

6.2 StringBuffer类常用方法

1) StringBuffer append(String s):String对象s的字符序列追加到当前StringBuffer对象的字符序列中,并返回当前StringBuffer对象的引用

   StringBuffer append(int n):int型数据n转化为String对象,再把该String对象的字符序列追加到当前StringBuffer对象的字符序列中,并返回当前StringBuffer对象的引用

   StringBuffer append(Object o):将一个Object对象o的字符序列表示追加到当前String- Buffer对象的字符序列中,并返回当前StringBuffer对象的引用

类似的方法还有:

   StringBuffer append(long n),StringBuffer append(boolean n),

   StringBuffer append(float n),StringBuffer append(double n),

   StringBuffer append(char n)

2)public chat charAt(int n ):得到参数n指定的置上的单个字符

   public void setCharAt(int n ,char ch):将当前StringBuffer对象实体中的字符串位置n处的字符用参数ch指定的字符替换

3)StringBuffer insert(int index, String str) :将参数str指定的字符串插入到参数index指定的位置

4)public StringBuffer reverse() :将该对象实体中的字符翻转

5)StringBuffer delete(int startIndex, int endIndex):从当前StringBuffer对象实体中的字符串中删除一个子字符串

   其相关方法:deleteCharAt(int index) 删除当前StringBuffer对象实体的字符串中index位置处的一个字符。

6)StringBuffer replace(int startIndex,int endIndex,String str):将当前StringBuffer对象实体中的字符串的一个子字符串用参数str指定的字符串替换   

public class Example8_14 {
   public static void main(String args[]) {
      StringBuffer str=new StringBuffer();
      str.append("大家好");
      System.out.println("str:"+str);
      System.out.println("length:"+str.length());
      System.out.println("capacity:"+str.capacity()); 
      str.setCharAt(0 ,'w'); 
      str.setCharAt(1 ,'e');
      System.out.println(str); 
      str.insert(2, " are all");
      System.out.println(str);
      int index=str.indexOf("好");
      str.replace(index,str.length()," right");
      System.out.println(str);
   }
}


7、Data和Calendar类

7.1 Data类

Date类的构造方法之一:

Date()使用Date类的无参数构造方法创建的对象可以获取本地当前时间。

     例: Date nowTime=new Date();

当前nowTime对象中含有的日期、时间就是创建nowTime对象时的本地计算机的日期和时间。

Date对象表示时间的默认顺序是:星期、月、日、小时、分、秒、年。

Date类的构造方法之二:

Date(long time)使用long型参数创建指定的时间

计算机系统将其自身的时间的“公元”设置在1970110时(格林威治时间),可以根据这个时间使用Date的带参数的构造方法:Date(long time)来创建一个Date对象,

              例如:Date date1=new Date(1000), date2=new Date(-1000);

其中的参数取正数表示公元后的时间,取负数表示公元前的时间,其中1000表示1000毫秒,那么,date1含有的日期、时间就是计算机系统公元后1秒时刻的日期、时间。

如果运行Java程序的本地时区是北京时区(与格林威治时间相差8个小时),那么上述date1就是19700101080001秒、date2就是19700101075959秒。

System类的静态方法 public long currentTimeMillis() 获取系统当前时间。

7.2Calendar类

Calendarjava.util包中。

使用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)

其作用是将日历翻到任何一个时间

calendar对象可以调用方法:

public long getTimeInMillis() 可以将时间表示为毫秒。

public final void setTime(Date date)使用给定的 Date 设置此 Calendar 的时间

public int get(int field) :可以获取有关年份、月份、小时、星期等信息。

例如:calendar.get(Calendar.MONTH); 返回一个整数,如果该整数是0表示当前日历是在一月,该整数是1表示当前日历是在二月等。

例如:calendar.get(Calendar.DAY_OF_WEEK);返回一个整数,如果该整数是1表示星期日,如果是2表示是星期一,依次类推,如果是7表示是星期六。

7.3 日期格式化

format方法

Formatter类的format方法:

format(格式化模式, 日期列表)

按着格式化模式返回日期列表中所列各个日期中所含数据(年,月,日,小时等数据)的字符串表示。

Java已经将format方法做为了String类的静态方法,因此,程序可以直接使用String类调用format方法对日期进行格式化。

1)格式化模式

format方法中的“格式化模式”是一个用双引号括起的字符序列(字符串),该字符序列中的字符由时间格式符和普通字符所构成。例如:"日期:%ty-%tm-%td"

String s = String.format("%tY%tm%td",new Date(),new Date(),new Date()); 

2)日期列表

format方法中的“日期列表”可以是用逗号分隔的Calendar对象或Date对象。

format方法默认按从左到右的顺序使用“格式化模式”中的格式符来格式“日期列表”中对应的日期,而“格式化模式”中的普通字符保留原样。

3)格式化同一日期     

可以在“格式化模式”中使用“<”,比如:"%ty-%<tm-%<td"中的三个格式符将格式化同一日期,即含有“<”的格式符和它前面的格式符格式同一个日期,例如:String s = String.format("%ty%<tm%<td",new Date());那么%<tm%<td都格式化new Date()。

7.4 不同区域的星期各式

如果想用特定地区的星期格式来表示日期中的星期,可以用format的重载方法:

         format (Locale locale,格式化模式,日期列表);

其中的参数locale是一个Locale类的实例,用于表示地域。

Locale类的static常量都是Locale对象,其中US是表示美国的static常量。

  比如,假设当前时间是2011-02-10,对于(%ta表示简称的星期):

String s = String.format(Locale.US,"%ta(%<tF)",new Date());

那么s是"Thu(2011-02-10)",

对于(%tA表示全称的星期)

String s = String.format(Locale.JAPAN,"%tA(%<tF)",new Date());

那么s是"木曜日(2011-02-10)"。

注:如果format方法不使用Locale参数格式化日期,当前应用程序所在系统的地区设置是中国,那么相当于locale参数取Locale.CHINA。

 

9、Math、BigInteger和Random类

9.1 Math类

Math类在java.lang包中。Math类包含许多用来进行科学计算的类方法,这些方法可以直接通过类名调用。另外,Math类还有两个静态常量,它们分别是:

E   2.7182828284590452354和PI    3.14159265358979323846。

以下是Math类的常用类方法:

public static long abs(double a)  返回a的绝对值。

public static double max(double a,double b) 返回a、b的最大值。

public static double min(double a,double b) 返回a、b的最小值。

public static double random()  产生一个0到1之间的随机数(不包括0和1)。

public static double pow(double a,double b) 返回ab次幂。

public static double sqrt(double a) 返回a的平方根。

public static double log(double a)  返回a的对数

public static double sin(double a) 返回正弦值。

public static double asin(double a)  返回反正弦值

 

9.2 BigInteger类

java.math包中的BigInteger类提供任意精度的整数运算。可以使用构造方法:

public BigInteger(String val)  构造一个十进制的BigInteger对象。

以下是BigInteger类的常用类方法:

public BigInteger add(BigInteger val)  返回当前大整数对象与参数指定的大整数对象的和。

public BigInteger subtract(BigInteger val)返回当前大整数对象与参数指定的大整数对象的差。

public BigInteger multiply(BigInteger val)返回当前大整数对象与参数指定的大整数对象的积。

public BigInteger divide(BigInteger val)返回当前大整数对象与参数指定的大整数对象的商。

public BigInteger remainder(BigInteger val)返回当前大整数对象与参数指定的大整数对象的余。

public int compareTo(BigInteger val) 返回当前大整数对象与参数指定的大整数的比较结果,返回值是1、-1或0,分别表示当前大整数对象大于、小于或等于参数指定的大整数。

public BigInteger pow(int a)  返回当前大整数对象的a次幂。

public String toString()  返回当前大整数对象十进制的字符串表示。

public String toString(int p)  返回当前大整数对象p进制的字符串表示。

9.3 Random类

Java提供了更为灵活的用于获得随机数的Random类(该类在java.util包中)。 Random类的如下构造方法:

public Random();

public Random(long seed);使用参数seek指定的种子创建一个Random对

随机数生成器random调用不带参数的nextInt()方法

         Random random=new Random();

         random.nextInt();

返回一个0至n之间(包括0,但不包括n)的随机数 随机数生成器random调用带参数的nextInt(int m)方法(参数m必须取正整数值

random.nextInt(100);返回一个0至100之间的随机整数(包括0,但不包括100)

random.nextBoolean();返回一个随机boolean值。

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/Huangxu_MIKU/article/details/84783637