java字串、異常小練習--判斷qq是否合法

大資料-劉耀文發表於2018-09-11

/*
* 異常練習:判斷qq是否合法:
要求:1.首字母不能是0 2.全是數字 3.位數在5-13位
要求:使用異常求解
*/
package com.qianfeng.zy;

import java.util.Scanner;

public class Day11WorksT1Method2 {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入一個qq號:");
    String a = sc.nextLine();
    QQ qq = new QQ(a);

    try {
        qq.heFa(a);
        System.out.println("qq合法");
    } catch (WeiLingException e) {
        e.printStackTrace();
    } catch (ShuZiException e) {
        e.printStackTrace();
    } catch (WeiShuException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

class WeiLingException extends Exception {
public WeiLingException() {

}

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

}

class ShuZiException extends Exception {
public ShuZiException() {

}

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

}

class WeiShuException extends Exception {

public WeiShuException() {

}

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

}

class QQ{

String Q;

public QQ() {
    super();
}

public QQ(String q) {
    super();
    Q = q;
}

public String getQ() {
    return Q;
}

public void setQ(String q) {
    Q = q;
}

public boolean arr(String Q){
    for (int i = 0; i < Q.length(); i++) {
        if (Q.charAt(i)<'0' || Q.charAt(i)>'9') {
            return false;
        }
    }
    return true;
}

public void heFa(String Q) throws WeiLingException, ShuZiException, WeiShuException
{
    if(Q.substring(0, 1).equals("0")){
        throw new WeiLingException("qq不合法:首字母不能為0");
    }
    if(!arr(Q)){
        throw new ShuZiException("qq不合法:應全為數字");
    }
    if (Q.length()<5 || Q.length()>13) {
        throw new WeiShuException("qq不合法:應為5-13位");
    }

}

}

相關文章