字符串的切割

關於字符串的切割首先要明確目的;
1.應該按照什麼來切割
2.要切割成幾部分
3.並且要用什麼類型來裝 切割之後的字符串數組

 例如生日的格式:
        月/日

// 得到會員的生日
// 1.切割字符串,將切出的字符串存到一個火車中
    String[] strs = birthday.split("/");
// 2.獲得0號車廂中的字符串和 1號車廂中的字符串
   也就是通過切割之後的兩個部分 通過你按照"/"切割的AB部分
    String month = strs[0];// 火車中的0號車廂中的字符串
    String day = strs[1];// 火車中的1號車廂中的字符串   
// 3.將對應數組變成字符串
   將通過切割的字符串 month 和  day 傳進來 也就是AB部分
        int int_month = Integer.parseInt(month);
        int int_day = Integer.parseInt(day);   
//4.通過轉換之後的字符串數字變成了數字然後纔可以進行判斷使用

日期判斷
//判斷月份和日期的範圍
    if((int_month <1 || int_month >12)  &&  (int_day < 1||int_day> 30)){
        System.out.println("日期格式有誤!,請重新輸入");
    }

例題 錄入會員的生日和密碼 要求生日格式爲 (月/日)密碼要求在6~10位數之間

先編寫一個日期格式異常類
 class DateException extends Exception { 

         public DateException() {
                super();
            } 

         public DateException(String message) {
            super(message);
            }
 }

驗證生日格式 聲明異常 
 class date {
    public boolean validateBirth(String date) throws DateException(){ 
        boolean b = true;
            首先先判斷符號"/"的位置
        if(date.indexOF("/"!=2)){
            並且拋出異常
            throw new DateException("日期格式異常");
        } 
        然後開始切割字符串 通過方法split 按照("/")來切割 存放到一個字符串數組中
        String[] d = date.split("/") 
        然後通過方法parseint方法 將字符串 轉換成爲Int類型的數字
        int month = integer.parseInt(d[0])
        int day = integer.parseInt(d[1]) 
        if((month < 0 || month > 12) || (day < 0 || day > 31)){
            System.out.println("日期有誤");
            return false;
        } 
        System.out.println("您的生日是" + date); .
            return b;
    }
}  

驗證密碼格式 
public  boolean validatePwd(String pwd) {  
    boolean c =true; 
    if (((pwd.length() < 6) || (pwd.length() > 10))) {
        System.out.println("密碼不符合要求");
        return false; 
    } else {
        System.out.println("您的密碼是:" + pwd);
    } 
    return c ;
    }  

測試方法 
public static void main(String[] args) { 
    date d = new date();
    boolean flag = false; 
    Scanner sc = new Scanner(System.in); 
    System.out.println("請輸入會員格式爲:月/日");
    do {
        try {
            System.out.println("請輸入會員生日");
            String date = sc.next();
            System.out.println("請輸入會員密碼");
            String pwd = sc.next();
            d.validateBirth(date);
            d.validatePwd(pwd);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        } while (!flag);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章