6、常用类

6. 常用类

1、包装类:每种基本数据类型都对应着包装类,用来将基本类型的数据封装起来,完成对应的方法

     byte--Byte

     short--Short

     int--Integer

     long--Long

     float--Float

     double--Double

     char--Character

     boolean--Boolean

2String不可变字符串存储在方法区

     需要掌握很多的api方法

      StringBuffer:可变字符串线程安全的,效率低

      StringBuilder:可变字符串线程不安全效率高

3Date:util常用),sql

     1Date date  = new Date();显示的日期格式不是常见的

     2、日期的计数从19701100:00:00,统计的毫秒数

4Calendar日历类

     1、不能够new对象必须通过getInstance方法获取日历对象

     2、掌握api

     3、常量属性

5SimpleDateFormat格式化日期类可以指定显示的格式

     1parse(String string):将字符串转为日期类型

     2、format(Date date):将日期格式转为String输出

6、Math:数学的很多操作

7、Enum类:将所有可能的值列举出来,使用的时候通过枚举类的名称.来直接访问

1. Object

Object类(掌握)

   (1)Object是类层次结构的根类,所有的类都直接或者间接的继承自Object类。

   (2)Object类的构造方法有一个,并且是无参构造

      这其实就是理解当时我们说过,子类构造方法默认访问父类的构造是无参构造

   (3)要掌握的方法:

      A:toString()

        返回对象的字符串表示,默认是由类的全路径+'@'+哈希值的十六进制表示。

        这个表示其实是没有意义的,一般子类都会重写该方法。

        如何重写呢?过程我也讲解过了,基本上就是要求信息简单明了。

        但是最终还是自动生成。

      B:equals()

        比较两个对象是否相同。默认情况下,比较的是地址值是否相同。

        而比较地址值是没有意义的,所以,一般子类也会重写该方法。

        重写过程,我也详细的讲解和分析了。

        但是最终还是自动生成。

   (4)要了解的方法:

      A:hashCode() 返回对象的哈希值。不是实际地址值,可以理解为地址值。

      B:getClass() 返回对象的字节码文件对象,反射中我们会详细讲解 

      C:finalize() 用于垃圾回收,在不确定的时间

      D:clone() 可以实现对象的克隆,包括成员变量的数据复制,但是它和两个引用指向同一个对象是有区别的。

   (5)两个注意问题;

      A:直接输出一个对象名称,其实默认调用了该对象的toString()方法。

      B:面试题

        ==和equals()的区别?

        A:==

           基本类型:比较的是值是否相同

           引用类型:比较的是地址值是否相同

        B:equals()

           只能比较引用类型。默认情况下,比较的是地址值是否相同。但是,我们可以根据自己的需要重写该方法。

/*

 * Object:类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。

 * 每个类都直接或者间接的继承自Object类。

 *

 * Object类的方法:

 *       public int hashCode():返回该对象的哈希码值。

 *         注意:哈希值是根据哈希算法计算出来的一个值,这个值和地址值有关,但是不是实际地址值。

 *                    你可以理解为地址值。

 *

 *    public final Class getClass():返回此 Object 的运行时类

 *       Class类的方法:

 *         public String getName():以 String 的形式返回此 Class 对象所表示的实体

 */

public class StudentTest {

   public static void main(String[] args) {

      Student s1 = new Student();

      System.out.println(s1.hashCode()); // 11299397

      Student s2 = new Student();

      System.out.println(s2.hashCode());// 24446859

      Student s3 = s1;

      System.out.println(s3.hashCode()); // 11299397

      System.out.println("-----------");


      Student s = new Student();

      Class c = s.getClass();

      String str = c.getName();

      System.out.println(str); // cn.itcast_01.Student

     

      //链式编程

      String str2  = s.getClass().getName();

      System.out.println(str2);

   }

}

 

/*

 * public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。

 * 这个方法,默认情况下比较的是地址值。比较地址值一般来说意义不大,所以我们要重写该方法。

 * 怎么重写呢?

 *       一般都是用来比较对象的成员变量值是否相同。

 * 重写的代码优化:提高效率,提高程序的健壮性。

 * 最终版:

 *       其实还是自动生成。

 *

 * 看源码:

 *       public boolean equals(Object obj) {

 *         //this - s1

 *         //obj - s2

 *       return (this == obj);

 *   }

 *

 * ==:

 *       基本类型:比较的就是值是否相同

 *       引用类型:比较的就是地址值是否相同

 * equals:

 *       引用类型:默认情况下,比较的是地址值。

 *       不过,我们可以根据情况自己重写该方法。一般重写都是自动生成,比较对象的成员变量值是否相同

 */

public class StudentDemo {

   public static void main(String[] args) {

      Student s1 = new Student("林青霞", 27);

      Student s2 = new Student("林青霞", 27);

      System.out.println(s1 == s2); // false

      Student s3 = s1;

      System.out.println(s1 == s3);// true

      System.out.println("---------------");


      System.out.println(s1.equals(s2)); // obj = s2; //false

      System.out.println(s1.equals(s1)); // true

      System.out.println(s1.equals(s3)); // true

      Student s4 = new Student("风清扬",30);

      System.out.println(s1.equals(s4)); //false

     

      Demo d = new Demo();

      System.out.println(s1.equals(d)); //ClassCastException


   }

}

 

/*

 * protected void finalize():当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。用于垃圾回收,但是什么时候回收不确定。

 * protected Object clone():创建并返回此对象的一个副本。

 *    A:重写该方法

 *

 *  Cloneable:此类实现了 Cloneable 接口,以指示 Object.clone() 方法可以合法地对该类实例进行按字段复制。

 *    这个接口是标记接口,告诉我们实现该接口的类就可以实现对象的复制了。

 */

public class StudentDemo {

   public static void main(String[] args) throws CloneNotSupportedException {

      //创建学生对象

      Student s = new Student();

      s.setName("林青霞");

      s.setAge(27);

     

      //克隆学生对象

      Object obj = s.clone();

      Student s2 = (Student)obj;

      System.out.println("---------");

     

      System.out.println(s.getName()+"---"+s.getAge());

      System.out.println(s2.getName()+"---"+s2.getAge());

     

      //以前的做法

      Student s3 = s;

      System.out.println(s3.getName()+"---"+s3.getAge());

      System.out.println("---------");

     

      //其实是有区别的

      s3.setName("刘意");

      s3.setAge(30);

      System.out.println(s.getName()+"---"+s.getAge());

      System.out.println(s2.getName()+"---"+s2.getAge());

      System.out.println(s3.getName()+"---"+s3.getAge());

     

   }

}

2. Scanner

Scanner的使用(了解)

   (1)在JDK5以后出现的用于键盘录入数据的类。

   (2)构造方法:

      A:讲解了System.in这个东西。

        它其实是标准的输入流,对应于键盘录入

      B:构造方法

        InputStream is = System.in;

       

        Scanner(InputStream is)

      C:常用的格式

        Scanner sc = new Scanner(System.in);

   (3)基本方法格式:

      A:hasNextXxx() 判断是否是某种类型的

      B:nextXxx() 返回某种类型的元素

   (4)要掌握的两个方法

      A:public int nextInt()

      B:public String nextLine()

   (5)需要注意的小问题

      A:同一个Scanner对象,先获取数值,再获取字符串会出现一个小问题。

      B:解决方案:

        a:重新定义一个Scanner对象

        b:把所有的数据都用字符串获取,然后再进行相应的转换
 

/*

 * Scanner:用于接收键盘录入数据。

 *

 * 前面的时候:

 *       A:导包

 *       B:创建对象

 *       C:调用方法

 *

 * System类下有一个静态的字段:

 *       public static final InputStream in; 标准的输入流,对应着键盘录入。

 *

 *       InputStream is = System.in;

 *

 * class Demo {

 *       public static final int x = 10;

 *       public static final Student s = new Student();

 * }

 * int y = Demo.x;

 * Student s = Demo.s;

 *

 *

 * 构造方法:

 *       Scanner(InputStream source)

 */

public class ScannerDemo {

   public static void main(String[] args) {

      // 创建对象

      Scanner sc = new Scanner(System.in);


      int x = sc.nextInt();

     

      System.out.println("x:" + x);

   }

}

/*

 * 基本格式:

 *       public boolean hasNextXxx():判断是否是某种类型的元素

 *       public Xxx nextXxx():获取该元素

 *

 * 举例:用int类型的方法举例

 *       public boolean hasNextInt()

 *       public int nextInt()

 *

 * 注意:

 *       InputMismatchException:输入的和你想要的不匹配

 */

public class ScannerDemo {

   public static void main(String[] args) {

      // 创建对象

      Scanner sc = new Scanner(System.in);


      // 获取数据

      if (sc.hasNextInt()) {

        int x = sc.nextInt();

        System.out.println("x:" + x);

      } else {

        System.out.println("你输入的数据有误");

      }

   }

}


 

/*

 * 常用的两个方法:

 *       public int nextInt():获取一个int类型的值

 *       public String nextLine():获取一个String类型的值

 *

 * 出现问题了:

 *       先获取一个数值,在获取一个字符串,会出现问题。

 *       主要原因:就是那个换行符号的问题。

 * 如何解决呢?

 *       A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。

 *       B:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。

 */

public class ScannerDemo {

   public static void main(String[] args) {

      // 创建对象

      Scanner sc = new Scanner(System.in);


      // 获取两个int类型的值

      // int a = sc.nextInt();

      // int b = sc.nextInt();

      // System.out.println("a:" + a + ",b:" + b);

      // System.out.println("-------------------");


      // 获取两个String类型的值

      // String s1 = sc.nextLine();

      // String s2 = sc.nextLine();

      // System.out.println("s1:" + s1 + ",s2:" + s2);

      // System.out.println("-------------------");


      // 先获取一个字符串,在获取一个int值

      // String s1 = sc.nextLine();

      // int b = sc.nextInt();

      // System.out.println("s1:" + s1 + ",b:" + b);

      // System.out.println("-------------------");


      // 先获取一个int值,在获取一个字符串

      // int a = sc.nextInt();

      // String s2 = sc.nextLine();

      // System.out.println("a:" + a + ",s2:" + s2);

      // System.out.println("-------------------");


      int a = sc.nextInt();

      Scanner sc2 = new Scanner(System.in);

      String s = sc2.nextLine();

      System.out.println("a:" + a + ",s:" + s);

   }

}

 

3. String

String类的概述和使用(掌握)

   (1)多个字符组成的一串数据。其实它可以和字符数组进行相互转换。

   (2)构造方法:

      A:public String()

      B:public String(byte[] bytes)

      C:public String(byte[] bytes,int offset,int length)

      D:public String(char[] value)

      E:public String(char[] value,int offset,int count)

      F:public String(String original)

      下面的这一个虽然不是构造方法,但是结果也是一个字符串对象

      G:String s = "hello";

   (3)字符串的特点

      A:字符串一旦被赋值,就不能改变。

        注意:这里指的是字符串的内容不能改变,而不是引用不能改变。

      B:字面值作为字符串对象和通过构造方法创建对象的不同

        String s = new String("hello");和String s = "hello"的区别?

   (4)字符串的面试题(看程序写结果)

      A:==和equals()

        String s1 = new String("hello");

        String s2 = new String("hello");

        System.out.println(s1 == s2);// false

        System.out.println(s1.equals(s2));// true,底层重写了equals方法

 

        String s3 = new String("hello");

        String s4 = "hello";

        System.out.println(s3 == s4);// false

        System.out.println(s3.equals(s4));// true

 

        String s5 = "hello";

        String s6 = "hello";

        System.out.println(s5 == s6);// true

        System.out.println(s5.equals(s6));// true

      B:字符串的拼接

        String s1 = "hello";

        String s2 = "world";

        String s3 = "helloworld";

        System.out.println(s3 == s1 + s2);// false

        System.out.println(s3.equals((s1 + s2)));// true

 

        System.out.println(s3 == "hello" + "world");// true

        System.out.println(s3.equals("hello" + "world"));// true

   (5)字符串的功能(自己补齐方法中文意思)

      A:判断功能

        boolean equals(Object obj)

        boolean equalsIgnoreCase(String str)

        boolean contains(String str)

        boolean startsWith(String str)

        boolean endsWith(String str)

        boolean isEmpty()

      B:获取功能

        int length()

        char charAt(int index)

        int indexOf(int ch)

        int indexOf(String str)

        int indexOf(int ch,int fromIndex)

        int indexOf(String str,int fromIndex)

        String substring(int start)

        String substring(int start,int end)

      C:转换功能

        byte[] getBytes()

        char[] toCharArray()

        static String valueOf(char[] chs)

        static String valueOf(int i)

        String toLowerCase()

        String toUpperCase()

        String concat(String str)

      D:其他功能

        a:替换功能

           String replace(char old,char new)

           String replace(String old,String new)

        b:去空格功能

           String trim()

        c:按字典比较功能

           int compareTo(String str)

           int compareToIgnoreCase(String str)

 

   

/*

 * 字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。

 * 通过查看API,我们可以知道

 *       A:字符串字面值"abc"也可以看成是一个字符串对象。

 *       B:字符串是常量,一旦被赋值,就不能被改变。

 *

 * 构造方法:

 *       public String():空构造

 *    public String(byte[] bytes):把字节数组转成字符串

 *    public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串

 *    public String(char[] value):把字符数组转成字符串

 *    public String(char[] value,int index,int count):把字符数组的一部分转成字符串

 *    public String(String original):把字符串常量值转成字符串

 *

 * 字符串的方法:

 *       public int length():返回此字符串的长度。

 */

public class StringDemo {

   public static void main(String[] args) {

      // public String():空构造

      String s1 = new String();

      System.out.println("s1:" + s1);

      System.out.println("s1.length():" + s1.length());

      System.out.println("--------------------------");


      // public String(byte[] bytes):把字节数组转成字符串

      byte[] bys = { 97, 98, 99, 100, 101 };

      String s2 = new String(bys);

      System.out.println("s2:" + s2);

      System.out.println("s2.length():" + s2.length());

      System.out.println("--------------------------");


      // public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串

      // 我想得到字符串"bcd"

      String s3 = new String(bys, 1, 3);

      System.out.println("s3:" + s3);

      System.out.println("s3.length():" + s3.length());

      System.out.println("--------------------------");


      // public String(char[] value):把字符数组转成字符串

      char[] chs = { 'a', 'b', 'c', 'd', 'e', '爱', '林', '亲' };

      String s4 = new String(chs);

      System.out.println("s4:" + s4);

      System.out.println("s4.length():" + s4.length());

      System.out.println("--------------------------");


      // public String(char[] value,int index,int count):把字符数组的一部分转成字符串

      String s5 = new String(chs, 2, 4);

      System.out.println("s5:" + s5);

      System.out.println("s5.length():" + s5.length());

      System.out.println("--------------------------");

     

      //public String(String original):把字符串常量值转成字符串

      String s6 = new String("abcde");

      System.out.println("s6:" + s6);

      System.out.println("s6.length():" + s6.length());

      System.out.println("--------------------------");

     

      //字符串字面值"abc"也可以看成是一个字符串对象。

      String s7 = "abcde";

      System.out.println("s7:"+s7);

      System.out.println("s7.length():"+s7.length());

   }

}

/*

 * 字符串的特点:一旦被赋值,就不能改变。

 */

public class StringDemo {

   public static void main(String[] args) {

      String s = "hello";

      s += "world";

      System.out.println("s:" + s); // helloworld

   }

}

 

/*

 * String s = new String(“hello”)和String s = “hello”;的区别?

 * 有。前者会创建2个对象,后者创建1个对象。

 *

 * ==:比较引用类型比较的是地址值是否相同

 * equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。

 */

public class StringDemo2 {

   public static void main(String[] args) {

      String s1 = new String("hello");

      String s2 = "hello";


      System.out.println(s1 == s2);// false

      System.out.println(s1.equals(s2));// true

   }

}

 

/*

 * 看程序写结果

 */

public class StringDemo3 {

   public static void main(String[] args) {

      String s1 = new String("hello");

      String s2 = new String("hello");

      System.out.println(s1 == s2);// false

      System.out.println(s1.equals(s2));// true


      String s3 = new String("hello");

      String s4 = "hello";

      System.out.println(s3 == s4);// false

      System.out.println(s3.equals(s4));// true


      String s5 = "hello";

      String s6 = "hello";

      System.out.println(s5 == s6);// true

      System.out.println(s5.equals(s6));// true

   }

}

 

/*

 * 看程序写结果

 * 字符串如果是变量相加,先开空间,在拼接。

 * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。

 */

public class StringDemo4 {

   public static void main(String[] args) {

      String s1 = "hello";

      String s2 = "world";

      String s3 = "helloworld";

      System.out.println(s3 == s1 + s2);// false

      System.out.println(s3.equals((s1 + s2)));// true


      System.out.println(s3 == "hello" + "world");// false 这个我们错了,应该是true

      System.out.println(s3.equals("hello" + "world"));// true


      // 通过反编译看源码,我们知道这里已经做好了处理。

      // System.out.println(s3 == "helloworld");

      // System.out.println(s3.equals("helloworld"));

   }

}

 

 

/*

 * String类的判断功能:

 * boolean equals(Object obj):比较字符串的内容是否相同,区分大小写

 * boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写

 * boolean contains(String str):判断大字符串中是否包含小字符串

 * boolean startsWith(String str):判断字符串是否以某个指定的字符串开头

 * boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾

 * boolean isEmpty():判断字符串是否为空。

 *

 * 注意:

 *       字符串内容为空和字符串对象为空。

 *       String s = "";

 *       String s = null;

 */

public class StringDemo {

   public static void main(String[] args) {

      // 创建字符串对象

      String s1 = "helloworld";

      String s2 = "helloworld";

      String s3 = "HelloWorld";


      // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写

      System.out.println("equals:" + s1.equals(s2));

      System.out.println("equals:" + s1.equals(s3));

      System.out.println("-----------------------");


      // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写

      System.out.println("equals:" + s1.equalsIgnoreCase(s2));

      System.out.println("equals:" + s1.equalsIgnoreCase(s3));

      System.out.println("-----------------------");


      // boolean contains(String str):判断大字符串中是否包含小字符串

      System.out.println("contains:" + s1.contains("hello"));

      System.out.println("contains:" + s1.contains("hw"));

      System.out.println("-----------------------");


      // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头

      System.out.println("startsWith:" + s1.startsWith("h"));

      System.out.println("startsWith:" + s1.startsWith("hello"));

      System.out.println("startsWith:" + s1.startsWith("world"));

      System.out.println("-----------------------");


      // 练习:boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾这个自己玩


      // boolean isEmpty():判断字符串是否为空。

      System.out.println("isEmpty:" + s1.isEmpty());


      String s4 = "";

      String s5 = null;

      System.out.println("isEmpty:" + s4.isEmpty());

      // NullPointerException

      // s5对象都不存在,所以不能调用方法,空指针异常

      System.out.println("isEmpty:" + s5.isEmpty());

   }

}

 

 

/*

 * String类的获取功能

 * int length():获取字符串的长度。

 * char charAt(int index):获取指定索引位置的字符

 * int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。

 *       为什么这里是int类型,而不是char类型?

 *       原因是:'a'和97其实都可以代表'a'

 * int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。

 * int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。

 * int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。

 * String substring(int start):从指定位置开始截取字符串,默认到末尾。

 * String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。

 */

public class StringDemo {

   public static void main(String[] args) {

      // 定义一个字符串对象

      String s = "helloworld";


      // int length():获取字符串的长度。

      System.out.println("s.length:" + s.length());

      System.out.println("----------------------");


      // char charAt(int index):获取指定索引位置的字符

      System.out.println("charAt:" + s.charAt(7));

      System.out.println("----------------------");


      // int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。

      System.out.println("indexOf:" + s.indexOf('l'));

      System.out.println("----------------------");


      // int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。

      System.out.println("indexOf:" + s.indexOf("owo"));

      System.out.println("----------------------");


      // int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。

      System.out.println("indexOf:" + s.indexOf('l', 4));

      System.out.println("indexOf:" + s.indexOf('k', 4)); // -1

      System.out.println("indexOf:" + s.indexOf('l', 40)); // -1

      System.out.println("----------------------");


      // 自己练习:int indexOf(String str,int

      // fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。


      // String substring(int start):从指定位置开始截取字符串,默认到末尾。包含start这个索引

      System.out.println("substring:" + s.substring(5));

      System.out.println("substring:" + s.substring(0));

      System.out.println("----------------------");


      // String substring(int start,int

      // end):从指定位置开始到指定位置结束截取字符串。包括start索引但是不包end索引

      System.out.println("substring:" + s.substring(3, 8));

      System.out.println("substring:" + s.substring(0, s.length()));

   }

}

 

/*

 * 需求:遍历获取字符串中的每一个字符

 *

 * 分析:

 *       A:如何能够拿到每一个字符呢?

 *         char charAt(int index)

 *       B:我怎么知道字符到底有多少个呢?

 *         int length()

 */

public class StringTest {

   public static void main(String[] args) {

      // 定义字符串

      String s = "helloworld";

      // 如果长度特别长,我不可能去数,所以我们要用长度功能

      for (int x = 0; x < s.length(); x++) {

        // char ch = s.charAt(x);

        // System.out.println(ch);

        // 仅仅是输出,我就直接输出了

        System.out.println(s.charAt(x));

      }

   }

}

 

/*

 * 需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

 * 举例:

 *       "Hello123World"

 * 结果:

 *       大写字符:2个

 *       小写字符:8个

 *       数字字符:3个

 *

 * 分析:

 *       前提:字符串要存在

 *       A:定义三个统计变量

 *         bigCount=0

 *         smallCount=0

 *         numberCount=0

 *       B:遍历字符串,得到每一个字符。

 *         length()和charAt()结合

 *       C:判断该字符到底是属于那种类型的

 *         大:bigCount++

 *         小:smallCount++

 *         数字:numberCount++

 *

 *         这道题目的难点就是如何判断某个字符是大的,还是小的,还是数字的。

 *         ASCII码表:

 *            0  48

 *            A  65

 *            a  97

 *         虽然,我们按照数字的这种比较是可以的,但是想多了,有比这还简单的

 *            char ch = s.charAt(x);

 *

 *            if(ch>='0' && ch<='9') numberCount++

 *            if(ch>='a' && ch<='z') smallCount++

 *            if(ch>='A' && ch<='Z') bigCount++

 *    D:输出结果。

 *

 * 练习:把给定字符串的方式,改进为键盘录入字符串的方式。

 */

public class StringTest2 {

   public static void main(String[] args) {

      //定义一个字符串

      String s = "Hello123World";

     

      //定义三个统计变量

      int bigCount = 0;

      int smallCount = 0;

      int numberCount = 0;

     

      //遍历字符串,得到每一个字符。

      for(int x=0; x<s.length(); x++){

        char ch = s.charAt(x);

       

        //判断该字符到底是属于那种类型的

        if(ch>='a' && ch<='z'){

           smallCount++;

        }else if(ch>='A' && ch<='Z'){

           bigCount++;

        }else if(ch>='0' && ch<='9'){

           numberCount++;

        }

      }

     

      //输出结果。

      System.out.println("大写字母"+bigCount+"个");

      System.out.println("小写字母"+smallCount+"个");

      System.out.println("数字"+numberCount+"个");

   }

}

 

/*

 * String的转换功能:

 * byte[] getBytes():把字符串转换为字节数组。

 * char[] toCharArray():把字符串转换为字符数组。

 * static String valueOf(char[] chs):把字符数组转成字符串。

 * static String valueOf(int i):把int类型的数据转成字符串。

 *       注意:String类的valueOf方法可以把任意类型的数据转成字符串。

 * String toLowerCase():把字符串转成小写。

 * String toUpperCase():把字符串转成大写。

 * String concat(String str):把字符串拼接。

 */

public class StringDemo {

   public static void main(String[] args) {

      // 定义一个字符串对象

      String s = "JavaSE";


      // byte[] getBytes():把字符串转换为字节数组。

      byte[] bys = s.getBytes();

      for (int x = 0; x < bys.length; x++) {

        System.out.println(bys[x]);

      }

      System.out.println("----------------");


      // char[] toCharArray():把字符串转换为字符数组。

      char[] chs = s.toCharArray();

      for (int x = 0; x < chs.length; x++) {

        System.out.println(chs[x]);

      }

      System.out.println("----------------");


      // static String valueOf(char[] chs):把字符数组转成字符串。

      String ss = String.valueOf(chs);

      System.out.println(ss);

      System.out.println("----------------");


      // static String valueOf(int i):把int类型的数据转成字符串。

      int i = 100;

      String sss = String.valueOf(i);

      System.out.println(sss);

      System.out.println("----------------");


      // String toLowerCase():把字符串转成小写。

      System.out.println("toLowerCase:" + s.toLowerCase());

      System.out.println("s:" + s);

      // System.out.println("----------------");

      // String toUpperCase():把字符串转成大写。

      System.out.println("toUpperCase:" + s.toUpperCase());

      System.out.println("----------------");


      // String concat(String str):把字符串拼接。

      String s1 = "hello";

      String s2 = "world";

      String s3 = s1 + s2;

      String s4 = s1.concat(s2);

      System.out.println("s3:"+s3);

      System.out.println("s4:"+s4);

   }

}

 

/*

 * 需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)

 * 举例:

 *       helloWORLD

 * 结果:

 *       Helloworld

 *

 * 分析:

 *       A:先获取第一个字符

 *       B:获取除了第一个字符以外的字符

 *       C:把A转成大写

 *       D:把B转成小写

 *       E:C拼接D

 */

public class StringTest {

   public static void main(String[] args) {

      // 定义一个字符串

      String s = "helloWORLD";


      // 先获取第一个字符

      String s1 = s.substring(0, 1);

      // 获取除了第一个字符以外的字符

      String s2 = s.substring(1);

      // 把A转成大写

      String s3 = s1.toUpperCase();

      // 把B转成小写

      String s4 = s2.toLowerCase();

      // C拼接D

      String s5 = s3.concat(s4);

      System.out.println(s5);


      // 优化后的代码

      // 链式编程

      String result = s.substring(0, 1).toUpperCase()

           .concat(s.substring(1).toLowerCase());

      System.out.println(result);

   }

}

 

/*

 * String类的其他功能:

 *

 * 替换功能:

 * String replace(char old,char new)

 * String replace(String old,String new)

 *

 * 去除字符串两空格 

 * String trim()

 *

 * 按字典顺序比较两个字符串 

 * int compareTo(String str)

 * int compareToIgnoreCase(String str)

 */

public class StringDemo {

   public static void main(String[] args) {

      // 替换功能

      String s1 = "helloworld";

      String s2 = s1.replace('l', 'k');

      String s3 = s1.replace("owo", "ak47");

      System.out.println("s1:" + s1);

      System.out.println("s2:" + s2);

      System.out.println("s3:" + s3);

      System.out.println("---------------");


      // 去除字符串两空格

      String s4 = " hello world  ";

      String s5 = s4.trim();

      System.out.println("s4:" + s4 + "---");

      System.out.println("s5:" + s5 + "---");


      // 按字典顺序比较两个字符串

      String s6 = "hello";

      String s7 = "hello";

      String s8 = "abc";

      String s9 = "xyz";

      System.out.println(s6.compareTo(s7));// 0

      System.out.println(s6.compareTo(s8));// 7

      System.out.println(s6.compareTo(s9));// -16

   }

}

 

 

/*

 * 需求:把数组中的数据按照指定个格式拼接成一个字符串

 * 举例:

 *       int[] arr = {1,2,3}; 

 * 输出结果:

 *    "[1, 2, 3]"

 * 分析:

 *       A:定义一个字符串对象,只不过内容为空

 *       B:先把字符串拼接一个"["

 *       C:遍历int数组,得到每一个元素

 *       D:先判断该元素是否为最后一个

 *         是:就直接拼接元素和"]"

 *         不是:就拼接元素和逗号以及空格

 *       E:输出拼接后的字符串

 *

 * 把代码用功能实现。

 */

public class StringTest2 {

   public static void main(String[] args) {

      // 前提是数组已经存在

      int[] arr = { 1, 2, 3 };


      // 写一个功能,实现结果

      String result = arrayToString(arr);

      System.out.println("最终结果是:" + result);

   }


   /*

    * 两个明确: 返回值类型:String 参数列表:int[] arr

    */

   public static String arrayToString(int[] arr) {

      // 定义一个字符串

      String s = "";


      // 先把字符串拼接一个"["

      s += "[";


      // 遍历int数组,得到每一个元素

      for (int x = 0; x < arr.length; x++) {

        // 先判断该元素是否为最后一个

        if (x == arr.length - 1) {

           // 就直接拼接元素和"]"

           s += arr[x];

           s += "]";

        } else {

           // 就拼接元素和逗号以及空格

           s += arr[x];

           s += ", ";

        }

      }


      return s;

   }

}

 

 

/*

 * 字符串反转

 * 举例:键盘录入”abc”   

 * 输出结果:”cba”

 *

 * 分析:

 *       A:键盘录入一个字符串

 *       B:定义一个新字符串

 *       C:倒着遍历字符串,得到每一个字符

 *         a:length()和charAt()结合

 *         b:把字符串转成字符数组

 *       D:用新字符串把每一个字符拼接起来

 *       E:输出新串

 */

public class StringTest3 {

   public static void main(String[] args) {

      // 键盘录入一个字符串

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入一个字符串:");

      String line = sc.nextLine();


      /*

      // 定义一个新字符串

      String result = "";


      // 把字符串转成字符数组

      char[] chs = line.toCharArray();


      // 倒着遍历字符串,得到每一个字符

      for (int x = chs.length - 1; x >= 0; x--) {

        // 用新字符串把每一个字符拼接起来

        result += chs[x];

      }


      // 输出新串

      System.out.println("反转后的结果是:" + result);

      */


      // 改进为功能实现

      String s = myReverse(line);

      System.out.println("实现功能后的结果是:" + s);

   }


   /*

    * 两个明确: 返回值类型:String 参数列表:String

    */

   public static String myReverse(String s) {

      // 定义一个新字符串

      String result = "";


      // 把字符串转成字符数组

      char[] chs = s.toCharArray();


      // 倒着遍历字符串,得到每一个字符

      for (int x = chs.length - 1; x >= 0; x--) {

        // 用新字符串把每一个字符拼接起来

        result += chs[x];

      }

      return result;

   }

}


 

/*

 * 统计大串中小串出现的次数

 * 举例:

 *       在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"

 * 结果:

 *       java出现了5次

 *

 * 分析:

 *    前提:是已经知道了大串和小串。

 *

 *    A:定义一个统计变量,初始化值是0

 *    B:先在大串中查找一次小串第一次出现的位置

 *       a:索引是-1,说明不存在了,就返回统计变量

 *       b:索引不是-1,说明存在,统计变量++

 *   C:把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串

 *    D:回到B

 */

public class StringTest4 {

   public static void main(String[] args) {

      // 定义大串

      String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun";

      // 定义小串

      String minString = "java";


      // 写功能实现

      int count = getCount(maxString, minString);

      System.out.println("Java在大串中出现了:" + count + "次");

   }


   /*

    * 两个明确: 返回值类型:int 参数列表:两个字符串

    */

   public static int getCount(String maxString, String minString) {

      // 定义一个统计变量,初始化值是0

      int count = 0;

      // 先在大串中查找一次小串第一次出现的位置

      int index = maxString.indexOf(minString);

      // 索引不是-1,说明存在,统计变量++

      while (index != -1) {

        count++;

        // 把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值给大串

        int startIndex = index + minString.length();

        maxString = maxString.substring(startIndex);

        // 继续查

        index = maxString.indexOf(minString);

      }


      return count;

   }

}

 

4. Character

Character(了解)

   (1)Character构造方法  

      Character ch = new Character('a');

   (2)要掌握的方法:(自己补齐)

      A:判断给定的字符是否是大写

      B:判断给定的字符是否是小写

      C:判断给定的字符是否是数字字符

      D:把给定的字符转成大写

      E:把给定的字符转成小写

   (3)案例:

                统计字符串中大写,小写及数字字符出现的次数
 

/*

 * Character 类在对象中包装一个基本类型 char 的值

 * 此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然

 *

 * 构造方法:

 *       Character(char value)

 */

public class CharacterDemo {

   public static void main(String[] args) {

      // 创建对象

      // Character ch = new Character((char) 97);

      Character ch = new Character('a');

      System.out.println("ch:" + ch);

   }

}

 

/*

 * public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符

 * public static boolean isLowerCase(char ch):判断给定的字符是否是小写字符

 * public static boolean isDigit(char ch):判断给定的字符是否是数字字符

 * public static char toUpperCase(char ch):把给定的字符转换为大写字符

 * public static char toLowerCase(char ch):把给定的字符转换为小写字符

 */

public class CharacterDemo {

   public static void main(String[] args) {

      // public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符

      System.out.println("isUpperCase:" + Character.isUpperCase('A'));

      System.out.println("isUpperCase:" + Character.isUpperCase('a'));

      System.out.println("isUpperCase:" + Character.isUpperCase('0'));

      System.out.println("-----------------------------------------");

      // public static boolean isLowerCase(char ch):判断给定的字符是否是小写字符

      System.out.println("isLowerCase:" + Character.isLowerCase('A'));

      System.out.println("isLowerCase:" + Character.isLowerCase('a'));

      System.out.println("isLowerCase:" + Character.isLowerCase('0'));

      System.out.println("-----------------------------------------");

      // public static boolean isDigit(char ch):判断给定的字符是否是数字字符

      System.out.println("isDigit:" + Character.isDigit('A'));

      System.out.println("isDigit:" + Character.isDigit('a'));

      System.out.println("isDigit:" + Character.isDigit('0'));

      System.out.println("-----------------------------------------");

      // public static char toUpperCase(char ch):把给定的字符转换为大写字符

      System.out.println("toUpperCase:" + Character.toUpperCase('A'));

      System.out.println("toUpperCase:" + Character.toUpperCase('a'));

      System.out.println("-----------------------------------------");

      // public static char toLowerCase(char ch):把给定的字符转换为小写字符

      System.out.println("toLowerCase:" + Character.toLowerCase('A'));

      System.out.println("toLowerCase:" + Character.toLowerCase('a'));

   }

}


 

/*

 * 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)

 *

 * 分析:

 *       A:定义三个统计变量。

 *         int bigCont=0;

 *         int smalCount=0;

 *         int numberCount=0;

 *       B:键盘录入一个字符串。

 *       C:把字符串转换为字符数组。

 *       D:遍历字符数组获取到每一个字符

 *       E:判断该字符是

 *         大写  bigCount++;

 *         小写  smalCount++;

 *         数字  numberCount++;

 *       F:输出结果即可

 */

public class CharacterTest {

   public static void main(String[] args) {

      // 定义三个统计变量。

      int bigCount = 0;

      int smallCount = 0;

      int numberCount = 0;


      // 键盘录入一个字符串。

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入一个字符串:");

      String line = sc.nextLine();


      // 把字符串转换为字符数组。

      char[] chs = line.toCharArray();


      // 历字符数组获取到每一个字符

      for (int x = 0; x < chs.length; x++) {

        char ch = chs[x];


        // 判断该字符

        if (Character.isUpperCase(ch)) {

           bigCount++;

        } else if (Character.isLowerCase(ch)) {

           smallCount++;

        } else if (Character.isDigit(ch)) {

           numberCount++;

        }

      }


      // 输出结果即可

      System.out.println("大写字母:" + bigCount + "个");

      System.out.println("小写字母:" + smallCount + "个");

      System.out.println("数字字符:" + numberCount + "个");

   }

}


 

5. Integer

Integer(掌握)

(1)为了让基本类型的数据进行更多的操作,Java就为每种基本类型提供了对应的包装类类型

      byte     Byte

      short   Short

      int        Integer

      long          Long

      float   Float

      double     Double

      char          Character

      boolean    Boolean

(2)Integer的构造方法

      A:Integer i = new Integer(100);

      B:Integer i = new Integer("100");

      注意:这里的字符串必须是由数字字符组成

(3)String和int的相互转换

      A:String -- int    Integer.parseInt("100");

      B:int -- String    String.valueOf(100);

(4)其他的功能(了解)

      进制转换

(5)JDK5的新特性

      自动装箱 基本类型--引用类型

      自动拆箱 引用类型--基本类型    

      把下面的这个代码理解即可:

        Integer i = 100;

        i += 200;

(6)面试题

      -128到127之间的数据缓冲池问题

/*

 * 需求1:我要求大家把100这个数据的二进制,八进制,十六进制计算出来

 * 需求2:我要求大家判断一个数据是否是int范围内的。

 *       首先你的知道int的范围是多大?

 *

 * 为了对基本数据类型进行更多的操作,更方便的操作,Java就针对每一种基本数据类型提供了对应的类类型。包装类类型。

 * byte       Byte

 * short      Short

 * int        Integer

 * long       Long

 * float      Float

 * double        Double

 * char       Character

 * boolean    Boolean

 *

 * 用于基本数据类型与字符串之间的转换。

 */

public class IntegerDemo {

   public static void main(String[] args) {

      // 不麻烦的就来了

      // public static String toBinaryString(int i)

      System.out.println(Integer.toBinaryString(100));

      // public static String toOctalString(int i)

      System.out.println(Integer.toOctalString(100));

      // public static String toHexString(int i)

      System.out.println(Integer.toHexString(100));


      // public static final int MAX_VALUE

      System.out.println(Integer.MAX_VALUE);

      // public static final int MIN_VALUE

      System.out.println(Integer.MIN_VALUE);

   }

}

/*

 * Integer的构造方法:

 * public Integer(int value)

 * public Integer(String s)

 *       注意:这个字符串必须是由数字字符组成

 */

public class IntegerDemo {

   public static void main(String[] args) {

      // 方式1

      int i = 100;

      Integer ii = new Integer(i);

      System.out.println("ii:" + ii);


      // 方式2

      String s = "100";

      // NumberFormatException

      // String s = "abc";

      Integer iii = new Integer(s);

      System.out.println("iii:" + iii);

   }

}


 

/*

 * int类型和String类型的相互转换

 *

 * int -- String

 *       String.valueOf(number)

 *

 * String -- int

 *       Integer.parseInt(s)

 */

public class IntegerDemo {

   public static void main(String[] args) {

      // int -- String

      int number = 100;

      // 方式1

      String s1 = "" + number;

      System.out.println("s1:" + s1);

      // 方式2

      String s2 = String.valueOf(number);

      System.out.println("s2:" + s2);

      // 方式3

      // int -- Integer -- String

      Integer i = new Integer(number);

      String s3 = i.toString();

      System.out.println("s3:" + s3);

      // 方式4

      // public static String toString(int i)

      String s4 = Integer.toString(number);

      System.out.println("s4:" + s4);

      System.out.println("-----------------");


      // String -- int

      String s = "100";

      // 方式1

      // String -- Integer -- int

      Integer ii = new Integer(s);

      // public int intValue()

      int x = ii.intValue();

      System.out.println("x:" + x);

      //方式2

      //public static int parseInt(String s)

      int y = Integer.parseInt(s);

      System.out.println("y:"+y);

   }

}

 

 

/*

 * 常用的基本进制转换

 * public static String toBinaryString(int i)

 * public static String toOctalString(int i)

 * public static String toHexString(int i)

 *

 * 十进制到其他进制

 * public static String toString(int i,int radix)

 * 由这个我们也看到了进制的范围:2-36

 * 为什么呢?0,...9,a...z

 *

 * 其他进制到十进制

 * public static int parseInt(String s,int radix)

 */

public class IntegerDemo {

   public static void main(String[] args) {

      // 十进制到二进制,八进制,十六进制

      System.out.println(Integer.toBinaryString(100));

      System.out.println(Integer.toOctalString(100));

      System.out.println(Integer.toHexString(100));

      System.out.println("-------------------------");


      // 十进制到其他进制

      System.out.println(Integer.toString(100, 10));

      System.out.println(Integer.toString(100, 2));

      System.out.println(Integer.toString(100, 8));

      System.out.println(Integer.toString(100, 16));

      System.out.println(Integer.toString(100, 5));

      System.out.println(Integer.toString(100, 7));

      System.out.println(Integer.toString(100, -7));

      System.out.println(Integer.toString(100, 70));

      System.out.println(Integer.toString(100, 1));

      System.out.println(Integer.toString(100, 17));

      System.out.println(Integer.toString(100, 32));

      System.out.println(Integer.toString(100, 37));

      System.out.println(Integer.toString(100, 36));

      System.out.println("-------------------------");

     

      //其他进制到十进制

      System.out.println(Integer.parseInt("100", 10));

      System.out.println(Integer.parseInt("100", 2));

      System.out.println(Integer.parseInt("100", 8));

      System.out.println(Integer.parseInt("100", 16));

      System.out.println(Integer.parseInt("100", 23));

      //NumberFormatException

      //System.out.println(Integer.parseInt("123", 2));

   }

}

 

/*

 * JDK5的新特性

 * 自动装箱:把基本类型转换为包装类类型

 * 自动拆箱:把包装类类型转换为基本类型

 *

 * 注意一个小问题:

 *       在使用时,Integer  x = null;代码就会出现NullPointerException。

 *       建议先判断是否为null,然后再使用。

 */

public class IntegerDemo {

   public static void main(String[] args) {

      // 定义了一个int类型的包装类类型变量i

      // Integer i = new Integer(100);

      Integer ii = 100;

      ii += 200;

      System.out.println("ii:" + ii);


      // 通过反编译后的代码

      // Integer ii = Integer.valueOf(100); //自动装箱

      // ii = Integer.valueOf(ii.intValue() + 200); //自动拆箱,再自动装箱

      // System.out.println((new StringBuilder("ii:")).append(ii).toString());


      Integer iii = null;

      // NullPointerException

      if (iii != null) {

        iii += 1000;

        System.out.println(iii);

      }

   }

}

 

/*

 * 看程序写结果

 *

 * 注意:Integer的数据直接赋值,如果在-128到127之间,会直接从缓冲池里获取数据

 */

public class IntegerDemo {

   public static void main(String[] args) {

      Integer i1 = new Integer(127);

      Integer i2 = new Integer(127);

      System.out.println(i1 == i2);

      System.out.println(i1.equals(i2));

      System.out.println("-----------");


      Integer i3 = new Integer(128);

      Integer i4 = new Integer(128);

      System.out.println(i3 == i4);

      System.out.println(i3.equals(i4));

      System.out.println("-----------");


      Integer i5 = 128;

      Integer i6 = 128;

      System.out.println(i5 == i6);

      System.out.println(i5.equals(i6));

      System.out.println("-----------");


      Integer i7 = 127;

      Integer i8 = 127;

      System.out.println(i7 == i8);

      System.out.println(i7.equals(i8));


      // 通过查看源码,我们就知道了,针对-128到127之间的数据,做了一个数据缓冲池,如果数据是该范围内的,每次并不创建新的空间

      // Integer ii = Integer.valueOf(127);

   }

}

------------------------------------

false

true

-----------

false

true

-----------

false

true

-----------

true

true

 

6. StringBuffer

StringBuffer(掌握)

   (1)用字符串做拼接,比较耗时并且也耗内存,而这种拼接操作又是比较常见的,为了解决这个问题,Java就提供了

      一个字符串缓冲区类。StringBuffer供我们使用。

   (2)StringBuffer的构造方法

      A:StringBuffer()

      B:StringBuffer(int size)

      C:StringBuffer(String str)

   (3)StringBuffer的常见功能(自己补齐方法的声明和方法的解释)

      A:添加功能

      B:删除功能

      C:替换功能

      D:反转功能

      E:截取功能(注意这个返回值)

   (4)StringBuffer的练习(做一遍)

      A:String和StringBuffer相互转换

        String -- StringBuffer

           构造方法

        StringBuffer -- String

           toString()方法

      B:字符串的拼接

      C:把字符串反转

      D:判断一个字符串是否对称

   (5)面试题

      小细节:

        StringBuffer:同步的,数据安全,效率低。

        StringBuilder:不同步的,数据不安全,效率高。

      A:String,StringBuffer,StringBuilder的区别

      B:StringBuffer和数组的区别?

   (6)注意的问题:

      String作为形式参数,StringBuffer作为形式参数。

 

 

/*

 * 线程安全(多线程讲解)

 * 安全 -- 同步 -- 数据是安全的

 * 不安全 -- 不同步 -- 效率高一些

 * 安全和效率问题是永远困扰我们的问题。

 * 安全:医院的网站,银行网站

 * 效率:新闻网站,论坛之类的

 *

 * StringBuffer:

 *       线程安全的可变字符串。

 *

 * StringBuffer和String的区别?

 * 前者长度和内容可变,后者不可变。

 * 如果使用前者做字符串的拼接,不会浪费太多的资源。

 *

 * StringBuffer的构造方法:

 *       public StringBuffer():无参构造方法

 *    public StringBuffer(int capacity):指定容量的字符串缓冲区对象

 *    public StringBuffer(String str):指定字符串内容的字符串缓冲区对象

 *

 * StringBuffer的方法:

 *    public int capacity():返回当前容量。 理论值

 *    public int length():返回长度(字符数)。 实际值

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // public StringBuffer():无参构造方法

      StringBuffer sb = new StringBuffer();

      System.out.println("sb:" + sb);

      System.out.println("sb.capacity():" + sb.capacity());

      System.out.println("sb.length():" + sb.length());

      System.out.println("--------------------------");


      // public StringBuffer(int capacity):指定容量的字符串缓冲区对象

      StringBuffer sb2 = new StringBuffer(50);

      System.out.println("sb2:" + sb2);

      System.out.println("sb2.capacity():" + sb2.capacity());

      System.out.println("sb2.length():" + sb2.length());

      System.out.println("--------------------------");


      // public StringBuffer(String str):指定字符串内容的字符串缓冲区对象

      StringBuffer sb3 = new StringBuffer("hello");

      System.out.println("sb3:" + sb3);

      System.out.println("sb3.capacity():" + sb3.capacity());

      System.out.println("sb3.length():" + sb3.length());

   }

}

 

/*

 * StringBuffer的添加功能:

 * public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身

 *

 * public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // 创建字符串缓冲区对象

      StringBuffer sb = new StringBuffer();


      // public StringBuffer append(String str)

      // StringBuffer sb2 = sb.append("hello");

      // System.out.println("sb:" + sb);

      // System.out.println("sb2:" + sb2);

      // System.out.println(sb == sb2); // true


      // 一步一步的添加数据

      // sb.append("hello");

      // sb.append(true);

      // sb.append(12);

      // sb.append(34.56);


      // 链式编程

      sb.append("hello").append(true).append(12).append(34.56);

      System.out.println("sb:" + sb);


      // public StringBuffer insert(int offset,String

      // str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

      sb.insert(5, "world");

      System.out.println("sb:" + sb);

   }

}

 

/*

 * StringBuffer的删除功能

 * public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身

 * public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // 创建对象

      StringBuffer sb = new StringBuffer();


      // 添加功能

      sb.append("hello").append("world").append("java");

      System.out.println("sb:" + sb);


      // public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身

      // 需求:我要删除e这个字符,肿么办?

      // sb.deleteCharAt(1);

      // 需求:我要删除第一个l这个字符,肿么办?

      // sb.deleteCharAt(1);


      // public StringBuffer delete(int start,int

      // end):删除从指定位置开始指定位置结束的内容,并返回本身

      // 需求:我要删除world这个字符串,肿么办?

      // sb.delete(5, 10);


      // 需求:我要删除所有的数据

      sb.delete(0, sb.length());


      System.out.println("sb:" + sb);

   }

}

 

/*

 * StringBuffer的替换功能:

 * public StringBuffer replace(int start,int end,String str):从start开始到end用str替换

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // 创建字符串缓冲区对象

      StringBuffer sb = new StringBuffer();


      // 添加数据

      sb.append("hello");

      sb.append("world");

      sb.append("java");

      System.out.println("sb:" + sb);


      // public StringBuffer replace(int start,int end,String

      // str):从start开始到end用str替换

      // 需求:我要把world这个数据替换为"节日快乐"

      sb.replace(5, 10, "节日快乐");

      System.out.println("sb:" + sb);

   }

}

 

/*

 * StringBuffer的反转功能:

 * public StringBuffer reverse()

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // 创建字符串缓冲区对象

      StringBuffer sb = new StringBuffer();


      // 添加数据

      sb.append("霞青林爱我");

      System.out.println("sb:" + sb);


      // public StringBuffer reverse()

      sb.reverse();

      System.out.println("sb:" + sb);

   }

}

 

/*

 * StringBuffer的截取功能:注意返回值类型不再是StringBuffer本身了

 * public String substring(int start)

 * public String substring(int start,int end)

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      // 创建字符串缓冲区对象

      StringBuffer sb = new StringBuffer();


      // 添加元素

      sb.append("hello").append("world").append("java");

      System.out.println("sb:" + sb);


      // 截取功能

      // public String substring(int start)

      String s = sb.substring(5);

      System.out.println("s:" + s);

      System.out.println("sb:" + sb);


      // public String substring(int start,int end)

      String ss = sb.substring(5, 10);

      System.out.println("ss:" + ss);

      System.out.println("sb:" + sb);

   }

}

 


 

/*

 * 为什么我们要讲解类之间的转换:

 * A -- B的转换

 * 我们把A转换为B,其实是为了使用B的功能。

 * B -- A的转换

 * 我们可能要的结果是A类型,所以还得转回来。

 *

 * String和StringBuffer的相互转换?

 */

public class StringBufferTest {

   public static void main(String[] args) {

      // String -- StringBuffer

      String s = "hello";

      // 注意:不能把字符串的值直接赋值给StringBuffer

      // StringBuffer sb = "hello";

      // StringBuffer sb = s;

      // 方式1:通过构造方法

      StringBuffer sb = new StringBuffer(s);

      // 方式2:通过append()方法

      StringBuffer sb2 = new StringBuffer();

      sb2.append(s);

      System.out.println("sb:" + sb);

      System.out.println("sb2:" + sb2);

      System.out.println("---------------");


      // StringBuffer -- String

      StringBuffer buffer = new StringBuffer("java");

      // String(StringBuffer buffer)

      // 方式1:通过构造方法

      String str = new String(buffer);

      // 方式2:通过toString()方法

      String str2 = buffer.toString();

      System.out.println("str:" + str);

      System.out.println("str2:" + str2);

   }

}

 

/*

 * 把数组拼接成一个字符串

 */

public class StringBufferTest2 {

   public static void main(String[] args) {

      // 定义一个数组

      int[] arr = { 44, 33, 55, 11, 22 };


      // 定义功能

      // 方式1:用String做拼接的方式

      String s1 = arrayToString(arr);

      System.out.println("s1:" + s1);


      // 方式2:用StringBuffer做拼接的方式

      String s2 = arrayToString2(arr);

      System.out.println("s2:" + s2);

   }


   // 用StringBuffer做拼接的方式

   public static String arrayToString2(int[] arr) {

      StringBuffer sb = new StringBuffer();


      sb.append("[");

      for (int x = 0; x < arr.length; x++) {

        if (x == arr.length - 1) {

           sb.append(arr[x]);

        } else {

           sb.append(arr[x]).append(", ");

        }

      }

      sb.append("]");


      return sb.toString();

   }


   // 用String做拼接的方式

   public static String arrayToString(int[] arr) {

      String s = "";


      s += "[";

      for (int x = 0; x < arr.length; x++) {

        if (x == arr.length - 1) {

           s += arr[x];

        } else {

           s += arr[x];

           s += ", ";

        }

      }

      s += "]";


      return s;

   }

}

 

/*

 * 把字符串反转

 */

public class StringBufferTest3 {

   public static void main(String[] args) {

      // 键盘录入数据

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入数据:");

      String s = sc.nextLine();


      // 方式1:用String做拼接

      String s1 = myReverse(s);

      System.out.println("s1:" + s1);

      // 方式2:用StringBuffer的reverse()功能

      String s2 = myReverse2(s);

      System.out.println("s2:" + s2);

   }


   // 用StringBuffer的reverse()功能

   public static String myReverse2(String s) {

      // StringBuffer sb = new StringBuffer();

      // sb.append(s);


      // StringBuffer sb = new StringBuffer(s);

      // sb.reverse();

      // return sb.toString();


      // 简易版

      return new StringBuffer(s).reverse().toString();

   }


   // 用String做拼接

   public static String myReverse(String s) {

      String result = "";


      char[] chs = s.toCharArray();

      for (int x = chs.length - 1; x >= 0; x--) {

        // char ch = chs[x];

        // result += ch;

        result += chs[x];

      }


      return result;

   }

}

 

/*

 * 判断一个字符串是否是对称字符串

 * 例如"abc"不是对称字符串,"aba"、"abba"、"aaa"、"mnanm"是对称字符串

 *

 * 分析:

 *       判断一个字符串是否是对称的字符串,我只需要把

 *         第一个和最后一个比较

 *         第二个和倒数第二个比较

 *         ...

 *       比较的次数是长度除以2。

 */

public class StringBufferTest4 {

   public static void main(String[] args) {

      // 创建键盘录入对象

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入一个字符串:");

      String s = sc.nextLine();


      // 一个一个的比较

      boolean b = isSame(s);

      System.out.println("b:" + b);

     

      //用字符串缓冲区的反转功能

      boolean b2 = isSame2(s);

      System.out.println("b2:"+b2);

   }

  

   public static boolean isSame2(String s) {

      return new StringBuffer(s).reverse().toString().equals(s);

   }

  


   // public static boolean isSame(String s) {

   // // 把字符串转成字符数组

   // char[] chs = s.toCharArray();

   //

   // for (int start = 0, end = chs.length - 1; start <= end; start++, end--) {

   // if (chs[start] != chs[end]) {

   // return false;

   // }

   // }

   //

   // return true;

   // }


   public static boolean isSame(String s) {

      boolean flag = true;


      // 把字符串转成字符数组

      char[] chs = s.toCharArray();


      for (int start = 0, end = chs.length - 1; start <= end; start++, end--) {

        if (chs[start] != chs[end]) {

           flag = false;

           break;

        }

      }


      return flag;

   }

}


 

/*

 *

 * 1:String,StringBuffer,StringBuilder的区别?

 * A:String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。

 * B:StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高

 *

 * 2:StringBuffer和数组的区别?

 * 二者都可以看出是一个容器,装其他的数据。

 * 但是呢,StringBuffer的数据最终是一个字符串数据。

 * 而数组可以放置多种数据,但必须是同一种数据类型的。

 *

 * 3:形式参数问题

 * String作为参数传递

 * StringBuffer作为参数传递

 *

 * 形式参数:

 *       基本类型:形式参数的改变不影响实际参数

 *       引用类型:形式参数的改变直接影响实际参数

 *

 * 注意:

 *       String作为参数传递,效果和基本类型作为参数传递是一样的。

 */

public class StringBufferDemo {

   public static void main(String[] args) {

      String s1 = "hello";

      String s2 = "world";

      System.out.println(s1 + "---" + s2);// hello---world

      change(s1, s2);

      System.out.println(s1 + "---" + s2);// hello---world


      StringBuffer sb1 = new StringBuffer("hello");

      StringBuffer sb2 = new StringBuffer("world");

      System.out.println(sb1 + "---" + sb2);// hello---world

      change(sb1, sb2);

      System.out.println(sb1 + "---" + sb2);// hello---worldworld


   }


   public static void change(StringBuffer sb1, StringBuffer sb2) {

      sb1 = sb2;

      sb2.append(sb1);

   }


   public static void change(String s1, String s2) {

      s1 = s2;

      s2 = s1 + s2;

   }

}

 

7. BigDecimal

BigDecimal(理解)

   (1)浮点数据做运算,会丢失精度。所以,针对浮点数据的操作建议采用BigDecimal。(金融相关的项目)

   (2)构造方法

      A:BigDecimal(String s)

   (3)成员方法:

      A:加

      B:减

      C:乘

      D:除

      E:自己保留小数几位


/*

 * 看程序写结果:结果和我们想的有一点点不一样,这是因为float类型的数据存储和整数不一样导致的。它们大部分的时候,都是带有有效数字位。

 *

 * 由于在运算的时候,float类型和double很容易丢失精度,演示案例。所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal

 *

 * BigDecimal类:不可变的、任意精度的有符号十进制数,可以解决数据丢失问题。

 */

public class BigDecimalDemo {

   public static void main(String[] args) {

      System.out.println(0.09 + 0.01);

      System.out.println(1.0 - 0.32);

      System.out.println(1.015 * 100);

      System.out.println(1.301 / 100);


      System.out.println(1.0 - 0.12);

   }

}

import java.math.BigDecimal;


/*

 * 构造方法:

 *       public BigDecimal(String val)

 *

 * public BigDecimal add(BigDecimal augend)

 * public BigDecimal subtract(BigDecimal subtrahend)

 * public BigDecimal multiply(BigDecimal multiplicand)

 * public BigDecimal divide(BigDecimal divisor)

 * public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,几位小数,如何舍取

 */

public class BigDecimalDemo {

   public static void main(String[] args) {

      // System.out.println(0.09 + 0.01);

      // System.out.println(1.0 - 0.32);

      // System.out.println(1.015 * 100);

      // System.out.println(1.301 / 100);


      BigDecimal bd1 = new BigDecimal("0.09");

      BigDecimal bd2 = new BigDecimal("0.01");

      System.out.println("add:" + bd1.add(bd2));

      System.out.println("-------------------");


      BigDecimal bd3 = new BigDecimal("1.0");

      BigDecimal bd4 = new BigDecimal("0.32");

      System.out.println("subtract:" + bd3.subtract(bd4));

      System.out.println("-------------------");


      BigDecimal bd5 = new BigDecimal("1.015");

      BigDecimal bd6 = new BigDecimal("100");

      System.out.println("multiply:" + bd5.multiply(bd6));

      System.out.println("-------------------");


      BigDecimal bd7 = new BigDecimal("1.301");

      BigDecimal bd8 = new BigDecimal("100");

      System.out.println("divide:" + bd7.divide(bd8));

      System.out.println("divide:"

           + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));

      System.out.println("divide:"

           + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));

   }

}



 

8. BigInteger

BigInteger(理解)

   (1)针对大整数的运算

   (2)构造方法

      A:BigInteger(String s)

   (3)成员方法(自己补齐)

      A:加

      B:减

      C:乘

      D:除

      E:商和余数

import java.math.BigInteger;

/*

 * BigInteger:可以让超过Integer范围内的数据进行运算

 *

 * 构造方法:

 * BigInteger(String val)

 */

public class BigIntegerDemo {

   public static void main(String[] args) {

      // 这几个测试,是为了简单超过int范围内,Integer就不能再表示,所以就更谈不上计算了。

      // Integer i = new Integer(100);

      // System.out.println(i);

      // // System.out.println(Integer.MAX_VALUE);

      // Integer ii = new Integer("2147483647");

      // System.out.println(ii);

      // // NumberFormatException

      // Integer iii = new Integer("2147483648");

      // System.out.println(iii);


      // 通过大整数来创建对象

      BigInteger bi = new BigInteger("2147483648");

      System.out.println("bi:" + bi);

   }

}


 

import java.math.BigInteger;


/*

 * public BigInteger add(BigInteger val):加

 * public BigInteger subtract(BigInteger val):减

 * public BigInteger multiply(BigInteger val):乘

 * public BigInteger divide(BigInteger val):除

 * public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组

 */

public class BigIntegerDemo {

   public static void main(String[] args) {

      BigInteger bi1 = new BigInteger("100");

      BigInteger bi2 = new BigInteger("50");


      // public BigInteger add(BigInteger val):加

      System.out.println("add:" + bi1.add(bi2));

      // public BigInteger subtract(BigInteger val):加

      System.out.println("subtract:" + bi1.subtract(bi2));

      // public BigInteger multiply(BigInteger val):加

      System.out.println("multiply:" + bi1.multiply(bi2));

      // public BigInteger divide(BigInteger val):加

      System.out.println("divide:" + bi1.divide(bi2));


      // public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组

      BigInteger[] bis = bi1.divideAndRemainder(bi2);

      System.out.println("商:" + bis[0]);

      System.out.println("余数:" + bis[1]);

   }

}


 

9. Calendar

/*

 * Calendar:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

 *

 * public int get(int field):返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。

 */

public class CalendarDemo {

   public static void main(String[] args) {

      // 其日历字段已由当前日期和时间初始化:

      Calendar rightNow = Calendar.getInstance(); // 子类对象


      // 获取年

      int year = rightNow.get(Calendar.YEAR);

      // 获取月

      int month = rightNow.get(Calendar.MONTH);

      // 获取日

      int date = rightNow.get(Calendar.DATE);


      System.out.println(year + "年" + (month + 1) + "月" + date + "日");

   }

}

/*

 * abstract class Person { public static Person getPerson() { return new

 * Student(); } }

 *

 * class Student extends Person {

 *

 * }

 */
/*

 * public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。

 * public final void set(int year,int month,int date):设置当前日历的年月日

 */

public class CalendarDemo {

   public static void main(String[] args) {

      // 获取当前的日历时间

      Calendar c = Calendar.getInstance();

      // 获取年

      int year = c.get(Calendar.YEAR);

      // 获取月

      int month = c.get(Calendar.MONTH);

      // 获取日

      int date = c.get(Calendar.DATE);

      System.out.println(year + "年" + (month + 1) + "月" + date + "日");


      // // 三年前的今天

      // c.add(Calendar.YEAR, -3);

      // // 获取年

      // year = c.get(Calendar.YEAR);

      // // 获取月

      // month = c.get(Calendar.MONTH);

      // // 获取日

      // date = c.get(Calendar.DATE);

      // System.out.println(year + "年" + (month + 1) + "月" + date + "日");


      // 5年后的10天前

      c.add(Calendar.YEAR, 5);

      c.add(Calendar.DATE, -10);

      // 获取年

      year = c.get(Calendar.YEAR);

      // 获取月

      month = c.get(Calendar.MONTH);

      // 获取日

      date = c.get(Calendar.DATE);

      System.out.println(year + "年" + (month + 1) + "月" + date + "日");

      System.out.println("--------------");


      c.set(2011, 11, 11);

      // 获取年

      year = c.get(Calendar.YEAR);

      // 获取月

      month = c.get(Calendar.MONTH);

      // 获取日

      date = c.get(Calendar.DATE);

      System.out.println(year + "年" + (month + 1) + "月" + date + "日");

   }

}

/*

 * 获取任意一年的二月有多少天

 *

 * 分析:

 *       A:键盘录入任意的年份

 *       B:设置日历对象的年月日

 *         年就是A输入的数据

 *         月是2

 *         日是1

 *       C:把时间往前推一天,就是2月的最后一天

 *       D:获取这一天输出即可

 */

public class CalendarTest {

   public static void main(String[] args) {

      // 键盘录入任意的年份

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入年份:");

      int year = sc.nextInt();


      // 设置日历对象的年月日

      Calendar c = Calendar.getInstance();

      c.set(year, 2, 1); // 其实是这一年的3月1日

      // 把时间往前推一天,就是2月的最后一天

      c.add(Calendar.DATE, -1);


      // 获取这一天输出即可

      System.out.println(c.get(Calendar.DATE));

   }

}

 

10. Date_DateFormat

Date/DateFormat(掌握)

   (1)Date是日期类,可以精确到毫秒。

      A:构造方法

        Date()

        Date(long time)

      B:成员方法

        getTime()

        setTime(long time)

      C:日期和毫秒值的相互转换

      案例:你来到这个世界多少天了?

   (2)DateFormat针对日期进行格式化和针对字符串进行解析的类,但是是抽象类,所以使用其子类SimpleDateFormat

      A:SimpleDateFormat(String pattern) 给定模式

        yyyy-MM-dd HH:mm:ss

      B:日期和字符串的转换

        a:Date -- String

           format()

        b:String -- Date

           parse()

      C:案例:

                        制作了一个针对日期操作的工具类。

/*

 * Date:表示特定的瞬间,精确到毫秒。

 *

 * 构造方法:

 *       Date():根据当前的默认毫秒值创建日期对象

 *       Date(long date):根据给定的毫秒值创建日期对象

 */

public class DateDemo {

   public static void main(String[] args) {

      // 创建对象

      Date d = new Date();

      System.out.println("d:" + d);


      // 创建对象

      // long time = System.currentTimeMillis();

      long time = 1000 * 60 * 60; // 1小时

      Date d2 = new Date(time);

      System.out.println("d2:" + d2);

   }

}


/*

 * public long getTime():获取时间,以毫秒为单位

 * public void setTime(long time):设置时间

 *

 * 从Date得到一个毫秒值

 *       getTime()

 * 把一个毫秒值转换为Date

 *       构造方法

 *       setTime(long time)

 */

public class DateDemo {

   public static void main(String[] args) {

      // 创建对象

      Date d = new Date();


      // 获取时间

      long time = d.getTime();

      System.out.println(time);

      // System.out.println(System.currentTimeMillis());


      System.out.println("d:" + d);

      // 设置时间

      d.setTime(1000);

      System.out.println("d:" + d);

   }

}
/*

 * Date  --   String(格式化)

 *       public final String format(Date date)

 *

 * String -- Date(解析)

 *       public Date parse(String source)

 *

 * DateForamt:可以进行日期和字符串的格式化和解析,但是由于是抽象类,所以使用具体子类SimpleDateFormat。

 *

 * SimpleDateFormat的构造方法:

 *       SimpleDateFormat():默认模式

 *       SimpleDateFormat(String pattern):给定的模式

 *         这个模式字符串该如何写呢?

 *         通过查看API,我们就找到了对应的模式

 *         年 y

 *         月 M 

 *         日 d

 *         时 H

 *         分 m

 *         秒 s

 *

 *         2014年12月12日 12:12:12

 */

public class DateFormatDemo {

   public static void main(String[] args) throws ParseException {

      // Date -- String

      // 创建日期对象

      Date d = new Date();

      // 创建格式化对象

      // SimpleDateFormat sdf = new SimpleDateFormat();

      // 给定模式

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

      // public final String format(Date date)

      String s = sdf.format(d);

      System.out.println(s);

     

     

      //String -- Date

      String str = "2008-08-08 12:12:12";

      //在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配

      SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      Date dd = sdf2.parse(str);

      System.out.println(dd);

   }

}

/**

 * 这是日期和字符串相互转换的工具类

 */

public class DateUtil {

   private DateUtil() {

   }


   /**

    * 这个方法的作用就是把日期转成一个字符串

    *

    * @param d

    *            被转换的日期对象

    * @param format

    *            传递过来的要被转换的格式

    * @return 格式化后的字符串

    */

   public static String dateToString(Date d, String format) {

      // SimpleDateFormat sdf = new SimpleDateFormat(format);

      // return sdf.format(d);

      return new SimpleDateFormat(format).format(d);

   }


   /**

    * 这个方法的作用就是把一个字符串解析成一个日期对象

    *

    * @param s

    *            被解析的字符串

    * @param format

    *            传递过来的要被转换的格式

    * @return 解析后的日期对象

    * @throws ParseException

    */

   public static Date stringToDate(String s, String format)

        throws ParseException {

      return new SimpleDateFormat(format).parse(s);

   }

}

 

 

/*

 * 工具类的测试

 */

public class DateUtilDemo {

   public static void main(String[] args) throws ParseException {

      Date d = new Date();

      // yyyy-MM-dd HH:mm:ss

      String s = DateUtil.dateToString(d, "yyyy年MM月dd日 HH:mm:ss");

      System.out.println(s);


      String s2 = DateUtil.dateToString(d, "yyyy年MM月dd日");

      System.out.println(s2);


      String s3 = DateUtil.dateToString(d, "HH:mm:ss");

      System.out.println(s3);


      String str = "2014-10-14";

      Date dd = DateUtil.stringToDate(str, "yyyy-MM-dd");

      System.out.println(dd);

   }

}

/*

 * 算一下你来到这个世界多少天?

 *

 * 分析:

 *       A:键盘录入你的出生的年月日

 *       B:把该字符串转换为一个日期

 *       C:通过该日期得到一个毫秒值

 *       D:获取当前时间的毫秒值

 *       E:用D-C得到一个毫秒值

 *       F:把E的毫秒值转换为年

 *         /1000/60/60/24

 */

public class MyYearOldDemo {

   public static void main(String[] args) throws ParseException {

      // 键盘录入你的出生的年月日

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入你的出生年月日:");

      String line = sc.nextLine();


      // 把该字符串转换为一个日期

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      Date d = sdf.parse(line);


      // 通过该日期得到一个毫秒值

      long myTime = d.getTime();


      // 获取  当前时间的毫秒值

      long nowTime = System.currentTimeMillis();


      // 用D-C得到一个毫秒值

      long time = nowTime - myTime;


      // 把E的毫秒值转换为年

      long day = time / 1000 / 60 / 60 / 24;


      System.out.println("你来到这个世界:" + day + "天");

   }

}

 

11. Math

Math(掌握)

   (1)针对数学运算进行操作的类

   (2)常见方法(自己补齐)

      A:绝对值

      B:向上取整

      C:向下取整

      D:两个数据中的大值

      E:a的b次幂

      F:随机数

      G:四舍五入

      H:正平方根

   (3)案例:

      A:猜数字小游戏

      B:获取任意范围的随机数

/*

 * Math:用于数学运算的类。

 * 成员变量:

 *       public static final double PI

 *       public static final double E

 * 成员方法:

 *       public static int abs(int a):绝对值

 *    public static double ceil(double a):向上取整

 *    public static double floor(double a):向下取整

 *    public static int max(int a,int b):最大值 (min自学)

 *    public static double pow(double a,double b):a的b次幂

 *    public static double random():随机数 [0.0,1.0)

 *    public static int round(float a) 四舍五入(参数为double的自学)

 *    public static double sqrt(double a):正平方根

 */

public class MathDemo {

   public static void main(String[] args) {

      // public static final double PI

      System.out.println("PI:" + Math.PI);

      // public static final double E

      System.out.println("E:" + Math.E);

      System.out.println("--------------");


      // public static int abs(int a):绝对值

      System.out.println("abs:" + Math.abs(10));

      System.out.println("abs:" + Math.abs(-10));

      System.out.println("--------------");


      // public static double ceil(double a):向上取整

      System.out.println("ceil:" + Math.ceil(12.34));

      System.out.println("ceil:" + Math.ceil(12.56));

      System.out.println("--------------");


      // public static double floor(double a):向下取整

      System.out.println("floor:" + Math.floor(12.34));

      System.out.println("floor:" + Math.floor(12.56));

      System.out.println("--------------");


      // public static int max(int a,int b):最大值

      System.out.println("max:" + Math.max(12, 23));

      // 需求:我要获取三个数据中的最大值

      // 方法的嵌套调用

      System.out.println("max:" + Math.max(Math.max(12, 23), 18));

      // 需求:我要获取四个数据中的最大值

      System.out.println("max:"

           + Math.max(Math.max(12, 78), Math.max(34, 56)));

      System.out.println("--------------");


      // public static double pow(double a,double b):a的b次幂

      System.out.println("pow:" + Math.pow(2, 3));

      System.out.println("--------------");


      // public static double random():随机数 [0.0,1.0)

      System.out.println("random:" + Math.random());

      // 获取一个1-100之间的随机数

      System.out.println("random:" + ((int) (Math.random() * 100) + 1));

      System.out.println("--------------");


      // public static int round(float a) 四舍五入(参数为double的自学)

      System.out.println("round:" + Math.round(12.34f));

      System.out.println("round:" + Math.round(12.56f));

      System.out.println("--------------");

     

      //public static double sqrt(double a):正平方根

      System.out.println("sqrt:"+Math.sqrt(4));

   }

}
/*

 * 需求:请设计一个方法,可以实现获取任意范围内的随机数。

 *

 * 分析:

 *       A:键盘录入两个数据。

 *         int strat;

 *         int end;

 *       B:想办法获取在start到end之间的随机数

 *         我写一个功能实现这个效果,得到一个随机数。(int)

 *       C:输出这个随机数

 */

public class MathDemo {

   public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);

      System.out.println("请输入开始数:");

      int start = sc.nextInt();

      System.out.println("请输入结束数:");

      int end = sc.nextInt();


      for (int x = 0; x < 100; x++) {

        // 调用功能

        int num = getRandom(start, end);

        // 输出结果

        System.out.println(num);

      }

   }


   /*

    * 写一个功能 两个明确: 返回值类型:int 参数列表:int start,int end

    */

   public static int getRandom(int start, int end) {

      // 回想我们讲过的1-100之间的随机数

      // int number = (int) (Math.random() * 100) + 1;

      // int number = (int) (Math.random() * end) + start;

      // 发现有问题了,怎么办呢?

      int number = (int) (Math.random() * (end - start + 1)) + start;

      return number;

   }

}

 

12. Random

Random(理解)

   (1)用于产生随机数的类

   (2)构造方法:

      A:Random() 默认种子,每次产生的随机数不同

      B:Random(long seed) 指定种子,每次种子相同,随机数就相同

   (3)成员方法:

      A:int nextInt() 返回int范围内的随机数

                B:int nextInt(int n) 返回[0,n)范围内的随机数

/*

 * Random:产生随机数的类

 *

 * 构造方法:

 *       public Random():没有给种子,用的是默认种子,是当前时间的毫秒值

 *    public Random(long seed):给出指定的种子

 *

 *    给定种子后,每次得到的随机数是相同的。

 *

 * 成员方法:

 *       public int nextInt():返回的是int范围内的随机数

 *    public int nextInt(int n):返回的是[0,n)范围的内随机数

 */

public class RandomDemo {

   public static void main(String[] args) {

      // 创建对象

      // Random r = new Random();

      Random r = new Random(1111);


      for (int x = 0; x < 10; x++) {

        // int num = r.nextInt();

        int num = r.nextInt(100) + 1;

        System.out.println(num);

      }

   }

}

 

13. System

System(掌握)

   (1)系统类,提供了一些有用的字段和方法

   (2)成员方法(自己补齐)

      A:运行垃圾回收器

      B:退出jvm

      C:获取当前时间的毫秒值

      D:数组复制

/*

 * System类包含一些有用的类字段和方法。它不能被实例化。

 *

 * 方法:

 *       public static void gc():运行垃圾回收器。

 *    public static void exit(int status)

 *    public static long currentTimeMillis()

 *    public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

 */

public class SystemDemo {

   public static void main(String[] args) {

      Person p = new Person("赵雅芝", 60);

      System.out.println(p);


      p = null; // 让p不再指定堆内存

      System.gc();

   }

}


/*

 * System类包含一些有用的类字段和方法。它不能被实例化。

 *

 * 方法:

 *       public static void gc():运行垃圾回收器。

 *    public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。

 *    public static long currentTimeMillis():返回以毫秒为单位的当前时间

 *    public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

 */

public class SystemDemo {

   public static void main(String[] args) {

      // System.out.println("我们喜欢林青霞(东方不败)");

      // System.exit(0);

      // System.out.println("我们也喜欢赵雅芝(白娘子)");


      // System.out.println(System.currentTimeMillis());


      // 单独得到这样的实际目前对我们来说意义不大

      // 那么,它到底有什么作用呢?

      // 要求:请大家给我统计这段程序的运行时间

      long start = System.currentTimeMillis();

      for (int x = 0; x < 100000; x++) {

        System.out.println("hello" + x);

      }

      long end = System.currentTimeMillis();

      System.out.println("共耗时:" + (end - start) + "毫秒");

   }

}

/*

 * System类包含一些有用的类字段和方法。它不能被实例化。

 *

 * 方法:

 *       public static void gc():运行垃圾回收器。

 *    public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。

 *    public static long currentTimeMillis():返回以毫秒为单位的当前时间

 *    public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

 *         从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

 */

public class SystemDemo {

   public static void main(String[] args) {

      // 定义数组

      int[] arr = { 11, 22, 33, 44, 55 };

      int[] arr2 = { 6, 7, 8, 9, 10 };


      // 请大家看这个代码的意思

      System.arraycopy(arr, 1, arr2, 2, 2);


      System.out.println(Arrays.toString(arr));

      System.out.println(Arrays.toString(arr2));

   }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值