Java基础类库--类库使用案例分析

内容学习于:edu.aliyun.com


1. StringBuff类

  定义一个StringBuffer类对象,然后通过append()方法向对象中添加26个小写字母,要求每次只添加一次,共添加26次,然后按照逆序的方式输出,并且可以删除前5个字符。
  本操作主要是训练StringBuffer类中的处理方法,因为StringBuffer的主要特点是内容允许修改。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        StringBuffer buf = new StringBuffer();
        for (int x = 'a' ;x<='z';x++){
            buf.append((char)x);//循环添加
        }
        buf.reverse();//翻转
        buf.delete(0,5);//删除
        System.out.println(buf);
    }
}

结果:

utsrqponmlkjihgfedcba

2. 随机数组

  利用Random类产生5个1~30之间(包括1和30)的随机整数。
Random产生随机数的操作之中会包含有数字0,所以此时不应该存在有数字0的问题。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        int reasult[] = NumberFactor.create(5);
        System.out.println(Arrays.toString(reasult));
    }
}


class NumberFactor {
    private static Random random = new Random();


    public static int[] create(int len) {
        int[] data = new int[len];
        for (int i = 0; i < len; i++) {
            data[i] = random.nextInt(30) + 1;
        }
        return data;
    }
}

结果:

[5, 5, 17, 29, 11]

3. 验证邮箱

  输入一个Email地址,然后使用正则表达式验证该Email地址是否正确。
  对于此时的输入可以通过命令参数实现数据的输入,如果要想进行验证,最好的做法是设置一个单独的验证处理类。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        String email = "[email protected]";
        System.out.println(Validator.isEmail(email));
    }
}


class Validator {
    private static final String REGEX="\\w+@\\w+\\.\\w+";

    public static boolean isEmail(String str){
        if (str == null || "".equals(str)){
            return false;
        }
        return str.matches(REGEX);
    }
}

结果:

true

4. 扔硬币

  编写程序,用0~1之间的随机数来模拟扔硬币试验,统计扔1000次后出现正、反面的次数并输出。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        Coin coin = new Coin();
        coin.throwCoins(1000);
        System.out.println("【正面的次数】:" + coin.getFront() + "、【反面的次数】:" + coin.getBack());
    }
}


class Coin {
    private int front;//正面的次数
    private int back;//反面的次数
    private Random random = new Random();

    public void throwCoins(int num) {
        for (int x = 0; x < num; x++) {
            if (this.random.nextInt(2) == 0) {
                front++;
            } else back++;
        }
    }

    public int getFront() {
        return front;
    }

    public int getBack() {
        return back;
    }
}

结果:

【正面的次数】:499、【反面的次数】:501

5. IP验证

  编写正则表达式,判断给定的是否是一个合法的IP地址。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        String ip1 = "266.115.0.6";
        String ip2 = "198.11.69.34";
        System.out.println(Validator.isIP(ip1));
        System.out.println(Validator.isIP(ip2));
    }
}


class Validator {


    public static boolean isIP(String ip) {
        if (ip == null || "".equals(ip)) {
            return false;
        }
        String regex = "([12]?[0-9]?[0-9]\\.){3}([12]?[0-9]?[0-9])";
        if (ip.matches(regex)) {
            String result[] = ip.split("\\.");
            for (String temp : result) {
                int x = Integer.parseInt(temp);
                if (x > 255) {
                    return false;
                }
            }
        }
        return true;
    }
}

结果:

false
true

6. 拆分html代码

  给定下面的HTML代码:

<font face= “Arial,Serif” size= ="+2" color=“red”>
要求对内容进行拆分,拆分之后的结果是:
face Arial,Serif
size +2
color red

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        String str = "<font face=\"Arial,Serif\" size=\"+2\" color=\"red\">";
        String regex = "\\w+=\"[a-zA-Z0-9+,]+\"";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String temp = matcher.group(0);
            String result[] = temp.split("=");
            System.out.println(result[0] + "\t" + result[1].replaceAll("\"", ""));
        }
    }
}

结果:

face Arial,Serif
size +2
color red

7. 国家代码

  编写程序,实现国际化应用,从命令行输入国家的代号,例如,1表示中国,2表示美国,然后根据输入代号的不同调用不同的资源文件显示信息。
  本程序的实现肯定要通过Locale类的对象来指定区域,随后利用ResourceBundle类加载资源文件。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        System.out.println(MessageUtil.getMessage(2));
    }
}

class MessageUtil {
    public static final int CHINA = 1;
    public static final int US = 2;
    private static final String KEY = "info";
    private static final String BASENAME = "com.xzzz.message.Messages";

    public static String getMessage(int num) {
        Locale locale = getLocal(num);
        if (locale == null)
            return "错误";
        return ResourceBundle.getBundle(BASENAME, locale).getString(KEY);

    }


    private static Locale getLocal(int num) {
        switch (num) {
            case CHINA:
                return new Locale("zh", "CN");
            case US:
                return new Locale("en", "US");

            default:
                return null;
        }
    }
}

结果:

Thanks Qiang,your ice-cream is very good!!!

8. 学生信息比较

  按照“姓名:年龄:成绩|姓名:年龄:成绩”的格式定义字符串“张三:21:98|李四:22: 89|王五:20:70",要求将每组值分别保存在Student对象之中,并对这些对象进行排序,排序的原则为:按照成绩由高到低排序,如果成绩相等,则按照年龄由低到高排序。
  本程序最典型的做法是直接利用比较器来完成处理,如果不使用比较器也可以完成,相当于自己采用冒泡的方式进行排列,使用了比较器就可以利用Arrays类做处理。

代码:

public class JavaAPIDemo {
    public static void main(String[] args) {
        String str = "张三:21:98|李四:22:89|王五:20:89";
        String result[] = str.split("\\|");
        Student student[] = new Student[result.length];
        for (int i = 0; i < result.length; i++) {
            String temp[] = result[i].split(":");
            student[i] = new Student(temp[0], Integer.parseInt(temp[1]), Double.parseDouble(temp[2]));
        }
        Arrays.sort(student);
        System.out.println(Arrays.toString(student));
    }
}

class Student implements Comparable<Student> {
    private String name;
    private int age;
    private double grade;

    public Student(String name, int age, double grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", grade=" + grade +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if (this.grade < o.grade)
            return 1;
        else if (this.grade > o.grade)
            return -1;
        else {
            return this.age - o.age;
        }
    }
}

结果:

[Student{name=‘张三’, age=21, grade=98.0}, Student{name=‘王五’, age=20, grade=89.0}, Student{name=‘李四’, age=22, grade=89.0}]

发布了43 篇原创文章 · 获赞 13 · 访问量 2652

猜你喜欢

转载自blog.csdn.net/qq_43040688/article/details/104065230