不二极端编程之Java基础工程详解

来源:互联网 发布:淘宝的广告位有哪些 编辑:程序博客网 时间:2024/05/17 03:35

基于JavaSE面向对象实现接收/传输/存储/修改数据等功能

Main:(主方法入口)

只需要编写注册登录的首页,达到预想的方法调用模式,就可以完成.

public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        while(true) { System.out.println("Ⅰ.注册\nⅡ.登录");            switch (scanner.nextInt()) {                case 1: scanner.nextLine();                    try { Console.inspect();//1.注册方法的调用                    } catch (IOException e) { e.printStackTrace();                    } catch (DocumentException e) { e.printStackTrace();                    } catch (UserDataException e) { System.out.println(e.getMessage()); }                    //关联注册操作的自定义异常                    break;                case 2: scanner.nextLine();                    try { Console.logIn();//2.登录方法的调用                    } catch (IOException e) { e.printStackTrace();                    } catch (DocumentException e) { e.printStackTrace();                    } catch (UserDataException e) { System.out.println(e.getMessage()); }                    //关联登录操作的自定义异常                    break;                default: System.out.println("选择操作错误!");                    break; } } }}

Console:(注册&登录方法的集成)

即1.&2.两种方法的实际编写流程以及扩展

public class Console {    static SAXReader saxReader = new SAXReader();    static File file = new File(Constant.USERDATA_PATH);    // 在main方法中调用的注册方法    public static void signIn() throws DocumentException, IOException, UserDataException {        Scanner scanner = new Scanner(System.in);        System.out.println("请输入账号:");        String newUserName = scanner.nextLine();        if (isPhone(newUserName)||isEmail(newUserName)){            if (inspect(newUserName)) { System.out.println("请输入密码:");                String newPassWord = scanner.nextLine();                if (isPassword(newPassWord)) { System.out.println("请输入用户昵称:");                    String newName = scanner.nextLine();                    if (isName(newName)) { System.out.println("用户注册成功!");                    // 注册成功以后将用户数据存入数据库XML中,此处调用资源类的注册方法                        Source.signIn(newUserName, newPassWord, newName);//1.资源类的注册方法                    } else { throw new NameInputErrorException(); }                } else { throw new PasswordInputErrorException(); }            }else{ throw new UserNameExistException(); }        }else { throw new UsernameInputErrorException(); }    }    // 在main方法中调用的登录方法    public static void logIn() throws DocumentException, UserDataException, IOException {        Scanner scanner = new Scanner(System.in);        System.out.println("请输入账号:");        // 此处接受控制台输入账号的同时,调用资源类的登录方法判断账号是否存在并接受返回值        UserData userData = Source.logIn(scanner.nextLine());//2.资源类的登录方法        if (userData != null){ System.out.println("请输入密码:");            String passWord = scanner.nextLine();            if (passWord.equals(userData.getPassWord())){ System.out.println("用户"+userData.getName()+"登录成功!");            // 登录成功后可以继续操作的功能                while(true) { System.out.println("请选择需要操作的功能:\nⅠ.查询天气\nⅡ.查询手机号归属地\nⅢ.手速游戏\nⅣ.查询手速游戏全国排行榜");                    switch (scanner.nextInt()) {                        // 此处为工具类的天气查询的方法的调用                        case 1: Visit.weatherFuture();                            break;                            // 此处为工具类的号码归属地的方法的调用                        case 2: Visit.phoneGet();                            break;                            // 此处为工具类的手速游戏的方法的调用                        case 3: Visit.startGame(userData.getName());                            break;                            // 此处为工具类的获取后端数据的方法的调用                        case 4: Visit.getTop();                            break;                        default: throw new SelectErrorException(); } }            } else{ throw new UserNameMismatchingPassWordException(); }        }else{ throw new UsernameInExistenceException(); }    }    // 以下所有方法为注册登录操作过程中设定的输入条件和判断以完善注册登录过程    // 用来判断注册过程中输入的账号是否已经存在    public static boolean inspect(String userName ) throws DocumentException {        Document read = saxReader.read(file);        Element rootElement = read.getRootElement();        List<Element> elements = rootElement.elements();        for (Element element : elements) {            String text = element.element("userName").getText();            if (text.equals(userName)){ System.out.println("账号已存在!");                return false; } }return true;    }    // 注册用户的昵称限制    public static boolean isName(String name){ return Pattern.matches(Constant.REGEX_NAME,name); }    // 注册用户的账号可为手机号    public static boolean isPhone(String userName){ return Pattern.matches(Constant.REGEX_PHONE, userName); }    // 注册用户的账号可为邮箱    public static boolean isEmail(String userName){ return Pattern.matches(Constant.REGEX_EMAIL,userName); }    // 注册用户的密码必须含有大小写字母和数字的组合    public static boolean isPassword(String passWord){ return Pattern.matches(Constant.REGEX_PASSWORD,passWord); }}

Source:(管控后台资源数据的注入和取出)

即1.&2.两种方法的区分和编写

public class Source {    static SAXReader saxReader = new SAXReader();    public static File file = new File(Constant.USERDATA_PATH);    // 接受控制台传输过来的数据存储近XML文件中    public static void signIn (String userName,String passWord,String name) throws DocumentException, IOException {        Document read = saxReader.read(file);        Element rootElement = read.getRootElement();        Element userData = rootElement.addElement(Constant.XML_ELEMENT_BY_ROOT);        userData.addAttribute(Constant.XML_ATTRIBUTE_BY_UD,name);        Element elementUserName = userData.addElement(Constant.XML_ELEMENT_BY_UD1);        Element elementPassWord = userData.addElement(Constant.XML_ELEMENT_BY_UD2);        elementUserName.addText(userName);        elementPassWord.addText(passWord);        OutputFormat outputFormat = OutputFormat.createPrettyPrint();        outputFormat.setEncoding(Constant.ENCODING);        XMLWriter xmlWriter = new XMLWriter(new FileWriter(Constant.USERDATA_PATH),outputFormat);        xmlWriter.write(read);        xmlWriter.close();    }     // 接受控制台传输过来的数据经过判断取出对应的数据以用来和接下来的接受做对比    public static UserData logIn (String name) throws DocumentException {        Document read = saxReader.read(file);        Element rootElement = read.getRootElement();        List <Element> elements = rootElement.elements();        for (Element element : elements) {            if (element.element(Constant.XML_ELEMENT_BY_UD1).getText().equals(name)){                Element userName = element.element(Constant.XML_ELEMENT_BY_UD1);                Element passWord = element.element(Constant.XML_ELEMENT_BY_UD2);                Attribute attribute = element.attribute(Constant.XML_ATTRIBUTE_BY_UD);                return new UserData(attribute.getValue(),userName.getText(),passWord.getText());            } }return null;}}

Visit:(集成功能工具的方法编写)

重点在于通过URL或者APL地址接口来获取远端数据或者传输数据

public class Visit {    public static void weatherFuture() throws IOException {        System.out.println("请输入需要查询的城市:");        Scanner scanner = new Scanner(System.in);        String city = scanner.nextLine();        URL u = new URL(Constant.API_APP+"weather.future&weaid="+city+Constant.API_APPKEY_SIGN);        String result = dataStore(u);        Map map = new HashMap();        map.put("result",Weather.ResultBean.class);        JSONObject jsonObject = JSONObject.fromObject(result);        Weather weather =(Weather) JSONObject.toBean(jsonObject, Weather.class,map);        List<Weather.ResultBean> resultBeans = weather.getResult();        for (Weather.ResultBean resultBean : resultBeans) {            System.out.println("日期:" + resultBean.getDays() + "\n星期:" + resultBean.getWeek() +                    "\n温度:"+resultBean.getTemperature()+"\n天气:"+resultBean.getWeather());        }    }    public static void phoneGet() throws IOException {        System.out.println("请输入需要查询的号码:");        Scanner scanner = new Scanner(System.in);        String phone = scanner.nextLine();        URL u = new URL(Constant.API_APP+"phone.get&phone="+phone+Constant.API_APPKEY_SIGN);        String result = dataStore(u);        JSONObject jsonObject = JSONObject.fromObject(result);        Telephone telephoneBelong = (Telephone)JSONObject.toBean(jsonObject, Telephone.class);        Telephone.ResultBean result1 = telephoneBelong.getResult();        System.out.println("手机号" + result1.getPhone() + "来自" + result1.getAtt() +                "\n号码源:" + result1.getOperators());    }    private static String dataStore(URL u) throws IOException {        InputStream in = u.openStream();        ByteArrayOutputStream out= new ByteArrayOutputStream();        try { byte buf[]= new byte[1024];            int read = 0;            while ((read = in.read(buf)) > 0) {                out.write(buf, 0, read); }        }finally { if (in != null) {                in.close(); } }        byte b[]=out.toByteArray( );        return new String(b, "utf-8");    }    public static void startGame(String username) throws IOException, DocumentException {        System.out.println("欢迎来到手速游戏测试平台:" +                "\n请选择游戏难度:" +                "\nⅠ.简单(10个字符)" +                "\nⅡ.一般(20个字符)" +                "\nⅢ.困难(30个字符)");        Scanner scanner = new Scanner(System.in);        int choice = scanner.nextInt();        for (int i = 3; i > 0; i--) {            try { Thread.sleep(1000);            } catch (InterruptedException e) { e.printStackTrace(); }            System.out.println("游戏"+i+"秒后开始");        }System.out.println("游戏正式开始!");        long timeBegin = new Date().getTime();        String list = duringGame(choice * 10);        scanner.nextLine();        if (scanner.nextLine().equals(list)){            long timeEnd = new Date().getTime();            long timeExpend = timeEnd - timeBegin;            System.out.println("恭喜你!成绩为:" + timeExpend + "毫秒");            Visit.submitScore(timeExpend,username);        }else { System.out.println("游戏失败!"); }    }    public static String duringGame(int number) throws IOException, DocumentException {        String [] gameList = new String[number];        String list = "";        for (int i = 0; i < gameList.length; i++) {            int random = 0;            if (number == 10){                random = (int)(Math.random()*36);//10+26            }else if (number == 20){                random = (int)(Math.random()*62);//10+26+26            }else if (number == 30){                random = (int)(Math.random()*86);//10+26+26+24            }            list = list + Constant.BYTES[random];        }        System.out.println(list);        return list;    }    public static void getTop() throws IOException, DocumentException {        URL url = new URL(Constant.URL_TOP_TEN);        URLConnection urlConnection = url.openConnection();        InputStream inputStream = urlConnection.getInputStream();        byte[] bytes = new byte[1024];        int read = inputStream.read(bytes);        String result = new String(bytes,0,read);        JSONArray jsonArray = JSONArray.fromObject(result);        for (int i = 0; i < jsonArray.size(); i++) {            JSONObject jsonObject = jsonArray.getJSONObject(i);            Ranking ranking = (Ranking)JSONObject.toBean(jsonObject, Ranking.class);            System.out.println("第"+(i+1)+"位用户名:"+ ranking.getNickname() +",分数为"+ ranking.getScore());        }    }    public static void submitScore(long time, String username) throws IOException, DocumentException {        URL url = new URL(Constant.URL_INSERT + "?username="+username+"&score="+time);        URLConnection urlConnection = url.openConnection();        InputStream inputStream = urlConnection.getInputStream();        byte[] bytes = new byte[1024];        int read = inputStream.read(bytes);        String result = new String(bytes,0,read,Constant.ENCODING);        if (result.equals("SUCCESS")){            System.out.println("成绩已提交成功!");            getFirst();        }else{            System.out.println("成绩提交失败!");        }    }    public static void getFirst() throws IOException, DocumentException {        SAXReader saxReader = new SAXReader();        Document document = saxReader.read(new URL(Constant.URL_FIRST));        Element rootElement = document.getRootElement();        String nickname = rootElement.element("nickname").getText();        String score = rootElement.element("score").getText();        System.out.println("目前第一名为:"+nickname+",分数为:"+score);    }}

Other:(其他工具类)

其中包含临时用户数据类/输入流和输出流的临时工具类/所有自定义异常类/常量类


用户数据类:

public class UserData {    private String name;    private String userName;    private String passWord;    @Override    public String toString() {        return "UserData{" +                "name='" + name + '\'' +                ", userName='" + userName + '\'' +                ", passWord='" + passWord + '\'' +                '}';    }    public UserData() {    }    public UserData(String name, String userName, String passWord) {        this.name = name;        this.userName = userName;        this.passWord = passWord;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassWord() {        return passWord;    }    public void setPassWord(String passWord) {        this.passWord = passWord;    }}

输入流和输出流的临时工具类

public class Weather {    private String success;    private List<ResultBean> result;    public String getSuccess() {        return success;    }    public void setSuccess(String success) {        this.success = success;    }    public List<ResultBean> getResult() {        return result;    }    public void setResult(List<ResultBean> result) {        this.result = result;    }    public static class ResultBean {        private String weaid;        private String days;        private String week;        private String cityno;        private String citynm;        private String cityid;        private String temperature;        private String humidity;        private String weather;        private String weather_icon;        private String weather_icon1;        private String wind;        private String winp;        private String temp_high;        private String temp_low;        private String humi_high;        private String humi_low;        private String weatid;        private String weatid1;        private String windid;        private String winpid;        public String getWeaid() {            return weaid;        }        public void setWeaid(String weaid) {            this.weaid = weaid;        }        public String getDays() {            return days;        }        public void setDays(String days) {            this.days = days;        }        public String getWeek() {            return week;        }        public void setWeek(String week) {            this.week = week;        }        public String getCityno() {            return cityno;        }        public void setCityno(String cityno) {            this.cityno = cityno;        }        public String getCitynm() {            return citynm;        }        public void setCitynm(String citynm) {            this.citynm = citynm;        }        public String getCityid() {            return cityid;        }        public void setCityid(String cityid) {            this.cityid = cityid;        }        public String getTemperature() {            return temperature;        }        public void setTemperature(String temperature) {            this.temperature = temperature;        }        public String getHumidity() {            return humidity;        }        public void setHumidity(String humidity) {            this.humidity = humidity;        }        public String getWeather() {            return weather;        }        public void setWeather(String weather) {            this.weather = weather;        }        public String getWeather_icon() {            return weather_icon;        }        public void setWeather_icon(String weather_icon) {            this.weather_icon = weather_icon;        }        public String getWeather_icon1() {            return weather_icon1;        }        public void setWeather_icon1(String weather_icon1) {            this.weather_icon1 = weather_icon1;        }        public String getWind() {            return wind;        }        public void setWind(String wind) {            this.wind = wind;        }        public String getWinp() {            return winp;        }        public void setWinp(String winp) {            this.winp = winp;        }        public String getTemp_high() {            return temp_high;        }        public void setTemp_high(String temp_high) {            this.temp_high = temp_high;        }        public String getTemp_low() {            return temp_low;        }        public void setTemp_low(String temp_low) {            this.temp_low = temp_low;        }        public String getHumi_high() {            return humi_high;        }        public void setHumi_high(String humi_high) {            this.humi_high = humi_high;        }        public String getHumi_low() {            return humi_low;        }        public void setHumi_low(String humi_low) {            this.humi_low = humi_low;        }        public String getWeatid() {            return weatid;        }        public void setWeatid(String weatid) {            this.weatid = weatid;        }        public String getWeatid1() {            return weatid1;        }        public void setWeatid1(String weatid1) {            this.weatid1 = weatid1;        }        public String getWindid() {            return windid;        }        public void setWindid(String windid) {            this.windid = windid;        }        public String getWinpid() {            return winpid;        }        public void setWinpid(String winpid) {            this.winpid = winpid;        }    }}

public class Telephone {    private String success;    private ResultBean result;    public String getSuccess() { return success; }    public void setSuccess(String success) { this.success = success; }    public ResultBean getResult() { return result; }    public void setResult(ResultBean result) { this.result = result; }    public static class ResultBean {        private String status;        private String phone;        private String area;        private String postno;        private String att;        private String ctype;        private String par;        private String prefix;        private String operators;        private String style_simcall;        private String style_citynm;        public String getStatus() {            return status;        }        public void setStatus(String status) {            this.status = status;        }        public String getPhone() {            return phone;        }        public void setPhone(String phone) {            this.phone = phone;        }        public String getArea() {            return area;        }        public void setArea(String area) {            this.area = area;        }        public String getPostno() {            return postno;        }        public void setPostno(String postno) {            this.postno = postno;        }        public String getAtt() {            return att;        }        public void setAtt(String att) {            this.att = att;        }        public String getCtype() {            return ctype;        }        public void setCtype(String ctype) {            this.ctype = ctype;        }        public String getPar() {            return par;        }        public void setPar(String par) {            this.par = par;        }        public String getPrefix() {            return prefix;        }        public void setPrefix(String prefix) {            this.prefix = prefix;        }        public String getOperators() {            return operators;        }        public void setOperators(String operators) {            this.operators = operators;        }        public String getStyle_simcall() {            return style_simcall;        }        public void setStyle_simcall(String style_simcall) {            this.style_simcall = style_simcall;        }        public String getStyle_citynm() {            return style_citynm;        }        public void setStyle_citynm(String style_citynm) {            this.style_citynm = style_citynm;        }    }}

public class Ranking {    private String nickname;    private int score;    public String getNickname() { return nickname; }    public void setNickname(String nickname) { this.nickname = nickname; }    public int getScore() { return score; }    public void setScore(int score) { this.score = score; }}

所有自定义异常类

public class UserDataException extends Exception { }
public class SignInException extends UserDataException { }
public class LogInException extends UserDataException { }
public class NameInputErrorException extends SignInException {    @Override    public String getMessage() {        return "昵称输入错误!";    }}
public class PasswordInputErrorException extends SignInException {    @Override    public String getMessage() {        return "密码输入错误!";    }}
public class SelectErrorException extends LogInException {    @Override    public String getMessage() {        return "选择操作错误!";    }}
public class UserNameExistException extends SignInException {    @Override    public String getMessage() {        return "账号已存在!";    }}
public class UsernameInExistenceException extends LogInException {    @Override    public String getMessage() {        return "账号不存在!";    }}
public class UsernameInputErrorException extends SignInException{    @Override    public String getMessage() {        return "账号输入错误!";    }}
public class UserNameMismatchingPassWordException extends LogInException {    @Override    public String getMessage() {        return "账号或者密码错误!";    }}

常量类

public class Constant {    public static final String USERDATA_PATH = "src\\com\\wsh\\user\\UserData.xml";    public static final String XML_ELEMENT_BY_ROOT = "userData";    public static final String XML_ATTRIBUTE_BY_UD = "name";    public static final String XML_ELEMENT_BY_UD1 = "userName";    public static final String XML_ELEMENT_BY_UD2 = "passWord";    public static final String ENCODING = "UTF-8";    public static final String REGEX_NAME = "^[a-zA-Z]\\w{5,20}$";    public static final String REGEX_PHONE = "^1[3,4,5,7,8,9]\\d{9}$";    public static final String REGEX_EMAIL = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";    public static final String REGEX_PASSWORD = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,14}";    public static final String URL_SITE = "http://192.168.20.194:8080";    public static final String URL_FIRST = URL_SITE + "/day16/first";    public static final String URL_TOP_TEN = URL_SITE + "/day16/ten";    public static final String URL_INSERT = URL_SITE + "/day16/insert";    public static final String API_APP = "http://api.k780.com/?app=";    public static final String API_APPKEY_SIGN = "&appkey=30513&sign=b91c1acd58df496d80253490ad9d5221&format=json";    public static final String[] BYTES = {            "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",            "1","2","3","4","5","6","7","8","9","0",            "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",            "~","!","@","#","$","%","^","&","*","(",")","_","+","{","}","[","]","<",">","?","/","|",",","."    };}