自定义异常,包装类,String

1.自定义异常
作用:就是为了能够在显示异常信息时,以中文的方式显示。
使用:
自定义一个类让当前类继承自异常父类或子类,然后重写父类的
构造方法,这就是一个自定义异常。

示例1:

/**
 * @author 
 * 自定义异常
 */
public class MyException extends RuntimeException{
public MyException() {
super();
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}


public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}

示例2:

/**
 * @author 
 * 自定义异常类  示例
 */
public class Test1 {
public static void main(String[] args) {
Test1 t=new Test1();
try{
t.display(0);
}catch(MyException ce){
ce.printStackTrace();
}
System.out.println("ok");
}
public void display(int num)throws MyException{
if(num==0){
throw new MyException("除数不能为零");
}else{
System.out.println(10/0);
}
}
}

2.包装类
java中所有的基本数据类型都有对应的包装类
byte---- Byte
short----Short
int      Integer
char     Character
long     Long
float    Float
double   Double
boolean  Boolean
通过包装类能够更加灵活的实现基本数据类型之间的转换,以及和其它
数据类型之间的转换。

装箱:从基本数据类型到所对应的包装类的过程
拆箱:从包装类到所对应的基本数据类型的过程
注意:装箱和拆箱是JDK5.0以后新增的特性。

示例:

public class Test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Integer对象
Integer num1=new Integer(10);
System.out.println(num1);
System.out.println(num1.intValue());
System.out.println(num1.longValue());
System.out.println(num1.doubleValue());
System.out.println(num1.floatValue());
System.out.println(num1.byteValue());
System.out.println(num1.toString()+10);
Integer num2=new Integer("123");
System.out.println(num2+1);
String str="456";
//转换成int类型
int num3=Integer.parseInt(str);
System.out.println(num3+1);
//Character
System.out.println(Character.isDigit('c'));
System.out.println(Character.isLetter('a'));
System.out.println(Character.isLowerCase('A'));
System.out.println(Character.isUpperCase('A'));
//装箱
int num4=10;
Integer i=num4;
System.out.println(i);
//拆箱
Double d=new Double(20.2);
double d2=d;
System.out.println(d2);
}
}


3.String类
由多个字符组成的序列就是字符串。
注意:在Java中字符串一定要使用双引号。
特点:
1.String是一个不可变的字符序列,也就是说String 这个类是一个final修饰的类。
2.使用String类是,需要注意对象的创建;字符串是一个特殊的类使用的过程中可以对String对象直接赋值;如果通过new String("字符串")的形式创建字符串对象,会产生两个队形,一个对象是构造方法中的参数,一个构造方法参数对象的副本。
3.String采用的Unicode国际统一编码。
4.字符串不可变的原因就是通过字符串池的原理实现的。

字符串池原理:在同一个项目中的所有字符串,实际上都会保存到同一个字符串池中,每声明一个字符串对象,都会和字符串池中已经存在的字符串进行比较,如果字符串池中已经存在,则直接引用已存在的字符串的内存地址;否则,把字符串存入字符串池中。

示例:

public class Test4 {
public static void main(String[] args) {
String str="abc";
str="456";
System.out.println(str.length());
        String s1 = "abc中文";
        String s2 = "abc中文";
        String s3 = "abc";
        System.out.println(s1 == s2); // ? 
        System.out.println(s1 == s3); // ? 
        System.out.println(s1.equals(s2)); // ? 
        System.out.println(s1.equals(s3)); // ?       
        String ss1 = new String("abc中文");
        String ss2 = new String("abc中文");
        String ss3 = new String("abc");
        System.out.println(ss1 == ss2); // ?
        System.out.println(ss1 == ss3); // ? 
        System.out.println(ss1.equals(ss2)); // ?
        System.out.println(ss1.equals(ss3)); // ?     
        System.out.println("abc".equals("ABC"));   
        System.out.println("ABC".equalsIgnoreCase("abc"));
        System.out.println("abc".compareTo("ab"));
        System.out.println("abc".compareTo("ade"));    
        System.out.println("abc".compareTo("Abc"));    
        System.out.println("abcdefg".startsWith("a"));
        System.out.println("abc".endsWith("c"));
}
}

4.String常用方法
length()判断字符串的长度
==:是用来判断两个字符串是否指向同一个内存地址.
equals()方法时用来判断两个字符串的内容是否一致。

compareTo()的返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的 
差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方 
全比较完,这时就比较字符的长度. 
例: 
String s1 = "abc"; 
String s2 = "abcd"; 
String s3 = "abcdfg"; 
String s4 = "1bcdfg"; 
String s5 = "cdfg"; 
System.out.println( s1.compareTo(s2) ); // -1 (前面相等,s1长度小1) 
System.out.println( s1.compareTo(s3) ); // -3 (前面相等,s1长度小3) 
System.out.println( s1.compareTo(s4) ); // 48 ("a"的ASCII码是97,"1"的的ASCII码是49,所以返回48) 
System.out.println( s1.compareTo(s5) ); // -2 ("a"的ASCII码是97,"c"的ASCII码是99,所以返回-2) 

示例1:

/**
 * @author 
 * 字符串搜索相关的方法
 * 验证邮箱格式是否正确,规则.com||.cn 在@符号的后面,符合这一规则的就是
 * 合法的邮箱。
 */
public class Test5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("abcaaa".indexOf("aaa"));
System.out.println("zhangsan".lastIndexOf('s'));
System.out.println("zhangsansanzhangsan".lastIndexOf("san"));
System.out.println("zhangsan".charAt(2));
}
public boolean display(String email){
boolean flag=false;
if(email.indexOf("@")<email.indexOf(".com")){
System.out.println("ok");
}else{

}
return flag;
}
}

示例2:

/**
 * @author 
 * 字符串修改相关的方法
 */
public class Test6 {
public static void main(String[] args) {
String str="zhangsanliswangwu";
System.out.println(str.substring(5));
System.out.println(str.substring(0, 6));
System.out.println(str.concat("tianqi"));
System.out.println("zhangsansansan".replace('a', 'c'));
String str2="    lisi   ";
System.out.println(str2.trim());
System.out.println("abc".toUpperCase());
System.out.println("HELLO".toLowerCase());
System.out.println(String.valueOf(10));
}
}


1. 使用JDK提供的一些很常用的类,主要通过阅读JavaSE API。
2. 基本数据类型的包装类:
   1) JDK为每一种基本数据类型都提供了一个对应的包装类。  .xxxValue();
   byte  --> java.lang.Byte
   short --> java.lang.Short
   int   --> java.lang.Integer         ☆
   long  --> java.lang.Long
   char  --> java.lang.Character       ☆
   float --> java.lang.Float
   double--> java.lang.Double
   boolean-> java.lang.Boolean
   2) 掌握各种基本类型数据和包装类之间的相互转换,与字符串之间的相互转换。
   3) JDK5.0中针对基本数据类型提供了一个新语法:自动装箱和自动拆箱。
      自动装箱:把基本类型的数据直接当作对应的包装类对象来使用。

      自动拆箱:把包装类对象直接当作对应的基本类型数据。


3.字符串相关类
 1) java.lang.String: 代表不可变的字符序列。特殊的引用数据类型。
     a) String str = "abc";  //最常用
        String str2 = new String("abc");
     b) 字符串可以使用“+”来连接:String str3 = "abc" + "中国";
        也可以用“+”跟其它类型数据进行连接:String str4 = "abc" + 12.345;
     c) String类有一个方法length()可以获取它的长度。 
        String str5 = "salkdf";
        str5.length();    // "salkdf".length();
     d) 字符串的比较
       ① == : 比较两个字符串的内存地址。  //用得少
       ② boolean equals(Object object): 比较的是两个字符串的内容。最常用的方法。
       ③ boolean equalsIgnoreCase(): 忽略大小写比较两个字符串的内容。
       ④ int compareTo(String str2): 比较两个字符串的字典顺序。
                                      如果相等,返回0
                                      如果在参数字符串位置之前,返回负数。
                                      如果在参数字符串位置之后,返回正数。 
       ⑤ int compareToIgnoreCase(String str2): 忽略大小写比较两个字符串的字典顺序。
       ⑥ boolean startsWith(String str): 是否以参数字符串开头

       ⑦ boolean endsWith(String str): 是否以参数字符串结尾

    e) 搜索字符串
       ① int indexOf(int ch): 搜索指定字符在本串中的索引(从0开始)
       ② int indexOf(String str): 搜索指定字符串在本串中的索引(从0开始)
       ③ int lastIndexOf(int ch)
       ④ int lastIndexOf(String str)

    f) 提取子字符串
       ① char charAt(int index): 提取指定索引处的那个字符。
       ② String substring(int beginIndex):提取从指定索引处到结尾的子串。
       ③ String substring(int beginIndex, int endIndex):提取从 beginindex开始直到 endindex(不包括此位置)之间的这部分字符串
       ④ String concat(String str):跟“+”的功能一样。
       ⑤ String replace(char oldChar,char newChar):返回一个新的字符串,它是通过用newChar 替换此字符串中出现的所有oldChar而生成的。 
       ⑥ String trim(); 去掉字符串的前后空格。
    g) 转大小写
       ① String toUpperCase(); 转成大写
       ② String toLowerCase(); 转成小写
    h) 其它类型转换成字符串: 
       static String valueOf(…)可以将基本类型数据、Object类型转换为字符串。
    i) 与正则表达式相关的方法:
       ① String[] split(String regex); 根据给定正则表达式的匹配拆分此字符串
       ② String replaceAll(String regex, String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串.
       ③ public boolean matches(String regex)告知此字符串是否匹配给定的正则表达式

    j) 如果要对字符串内容进行频繁的更改时,不建议使用“+”,而应该用StringBuffer或StringBuider类

示例1:

/**
 * @author
 * 字符串修改相关的方法
 */
public class Test6 {
public static void main(String[] args) {
String str="zhangsanliswangwu";
System.out.println(str.substring(5));
System.out.println(str.substring(0, 6));
System.out.println(str.concat("tianqi"));
System.out.println("zhangsansansan".replace('a', 'c'));
String str2="    lisi   ";
System.out.println(str2.trim());
System.out.println("abc".toUpperCase());
System.out.println("HELLO".toLowerCase());
System.out.println(String.valueOf(10));
}
}

示例2:

/**
 * @author 
 * split 方法
 */
public class Test7 {
public static void main(String[] args) {
String str="hello-world-ni-hao";
String[]s=str.split("-");
for(String a:s){
System.out.println(a);
}
}
}

示例3:

/**
 * @author 
 *编写一个java方法,用来统计所给字符串中大写英文字母的个数,
 *小写英文字母的个数以及数字的个数再以及特殊字符的个数。
 */
public class Test8 {
public static void main(String[] args) {
String str="AAKLDSJFewrqq@!$%^&*(asdfa89713461akshdf1234@#$%^";
//step1:如何获取字符串中的每个字符
char[]c=str.toCharArray();
int count1=0;//大写
int count2=0;//小写
int count3=0;//数字
int count4=0;//特殊字符
for(int i=0;i<c.length;i++){
if(Character.isUpperCase(c[i])){
count1++;
}else if(Character.isLowerCase(c[i])){
count2++;
}else if(Character.isDigit(c[i])){
count3++;
}else{
count4++;
}
}
System.out.println("大写:"+count1);
System.out.println("小写:"+count2);
System.out.println("数字:"+count3);
System.out.println("特殊字符:"+count4);
}
}

示例4:

/**
 * @author 
 * 有一个字符串 String str="welcome to beijing";把该字符串中每个单词的首字母改成大写
 * 其它不变,输出的结果应该是: Welcome To Beijing
 */
public class Test9 {
public static void main(String[] args) {
String str="welcome to beijing";
//step1:如何得到每个单词
String[]s=str.split(" ");
for(int i=0;i<s.length;i++){
System.out.print(s[i].substring(0, 1).toUpperCase().concat(s[i].substring(1))+"\t");
}
}
}

示例5:

import static java.lang.Math.*;
/**
 * @author lw
 * Math类示例
 * -11.5
 */
public class Test10 {
public static void main(String[] args) {
System.out.println(PI);
System.out.println(round(-11.4));
System.out.println(random());
}
}

示例6:

import java.util.Random;
/**
 * @author 
 * Random 随机数
 */
public class Test11 {
public static void main(String[] args) {
Random rd=new Random();
System.out.println(rd.nextInt(10));
System.out.println(rd.nextInt());
System.out.println(rd.nextBoolean());
Random rd2=new Random(10000000L);
Random rd3=new Random(10000000L);
System.out.println(rd2.nextInt());
System.out.println(rd3.nextInt());
}
}


作业:

/**
 * @author wx
 * 
 * 1. 编写一个方法:
  public static int count(String source, String key));从source字符串中查找key字符串出现的次数。
比如:
String source = "String testStringte st testString testString test";
String key = "test";
那么这个方法应该返回4。
 *
 */
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String source = "StringtestStringtesttestStringtestStringtestStringStringtesttest";
int c=count(source, "String");
System.out.println(c);
}

public static int count(String source, String key){
int index=source.indexOf(key, 0);
int c=0;
while(index!=-1){
c++;
index=source.indexOf(key, index+key.length());
}
return c;
}
}


2.编写一个方法public String  initcap(String word);  把整句话的每个单词的首字母改成大写,其它不变。

/**
 * @author wx
 * 有一个字符串 String str="welcome to beijing";把该字符串中每个单词的首字母改成大写
 * 其它不变,输出的结果应该是: Welcome To Beijing
 */
public class Test9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="welcome to beijing";
//step1:如何得到每个单词
String[]s=str.split(" ");
for(int i=0;i<s.length;i++){
System.out.print(s[i].substring(0, 1).toUpperCase().concat(s[i].substring(1))+"\t");
}
}
}

3.

import java.util.Random;

/**
 * @author wx
 * 编写一个Java方法,生成5个不重复的英文小写字母,并按字母顺序排列好。
 */
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
display();
}

public static void display(){
Random rd=new Random();
char[]c=new char[5];
for(int i=0;i<c.length;i++){
char temp=(char)(rd.nextInt(26)+97);
boolean f=validate(c, temp);
if(f){
--i;
continue;
}else{
c[i]=temp;
}
}

for(char a:c){
System.out.println(a);
}
}

/**
* 判断指定的数组中,是否已经存在指定的数据
* @param c
* @param a
* @return
*/
public static boolean validate(char[]c,char a){
boolean flag=false;
for(int i=0;i<c.length;i++){
if(c[i]==a){
flag=true;
break;
}

}
return flag;
}
}

4.

/**
 * @author wx
 *验证给定的用户名是否合法。合法用户名的要求是:只能以英字母开头,字符只能包括英文字母、数字和下划线,长度必须在6-20位之间。
 */
public class Test3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test3 t=new Test3();
boolean flag=t.display();
if(flag){
System.out.println("ok");
}else{
System.out.println("no ok");
}
}

public boolean display(){
boolean flag=false;
String name="Azhangsan_123";
if(name.length()>6&&name.length()<20){
char[]c=name.toCharArray();
if(Character.isLetter(c[0])){
for(int i=0;i<c.length;i++){
if(Character.isDigit(c[i])){
flag=true;
}else if(c[i]=='_'){
flag=true;
}else{
flag=false;
}
}
}else{
flag=false;
}
}
return flag;
}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章