1 package com.itheima;
2
3 import java.util.Iterator;
4 import java.util.Map;
5 import java.util.Map.Entry;
6 import java.util.TreeMap;
7
8 public class Test1 {
9
10 /**
11 * 1、 取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)...
12 * @author 汤柳清
13 */
14
15 public static void main(String[] args) {
16 String str = "abcdekka27qoq";
17 System.out.println(charCount(str));
18 }
19
20 public static String charCount(String str) {
21 char[] chs = str.toCharArray();//转换成数组
22 Map<Character, Integer> m = new TreeMap<Character, Integer>();//加入泛型,前一参数是字符类型,后一个参数是整型
23 int count = 0;
24 for (int x = 0; x < chs.length; x++) {
25 if (chs[x] >= 'a' && chs[x] <= 'z' || chs[x] >= 'A'
26 && chs[x] <= 'Z') {
27 Integer value = m.get(chs[x]);//得到key所对应的value
28 System.out.print(chs[x]+",");//查看key的值
29 System.out.println(value);//查看value的值
30 if (value != null)
31 count = value;
32 count++;
33 m.put(chs[x], count);
34 count = 0;//清0
35 }
36 }
37 StringBuilder sb = new StringBuilder();//保存将从集合中迭代出来的字母和次数
38 //迭代map集合
39 Iterator<Entry<Character, Integer>> it = m.entrySet().iterator();
40 while (it.hasNext()) {
41 Map.Entry<Character, Integer> me = it.next();
42 //加到容器sb中
43 sb.append(me.getKey() + "(" + me.getValue() + ")");
44 }
45 return sb.toString();
46
47 }
48 }
1 package com.itheima;
2
3 public class Test2 {
4
5 /**
6 * 2、 定义一个交通灯枚举,包含红灯、绿灯、黄灯,需要有获得下一个灯的方法,例如:红灯获取下一个灯是绿灯,绿灯获取下一个灯是黄灯。 分析:
7 * 1.定义一个交通灯枚举 2.枚举中包含3个对象即RED、GREEN、YELLOW
8 * 3.定义抽象方法nextLamp(),类型为TrafficLamp 4.用匿名内部类的方式为3个对象实现抽象方法 5.构造方法私有化
9 *
10 * @author 汤柳清
11 */
12 public static void main(String[] args) {
13 TrafficLamp t = TrafficLamp.RED;
14 System.out.println(t.nextLamp());
15
16 TrafficLamp t1 = TrafficLamp.GREEN;
17 System.out.println(t1.nextLamp());
18
19 TrafficLamp t2 = TrafficLamp.YELLOW;
20 System.out.println(t2.nextLamp());
21 }
22 }
23
24 enum TrafficLamp {
25 RED {// 匿名内部类
26 public TrafficLamp nextLamp() {
27 return GREEN;
28 }
29 },
30 GREEN() {// 匿名内部类
31 public TrafficLamp nextLamp() {
32 return YELLOW;
33 }
34 },
35 YELLOW() {// 匿名内部类
36 public TrafficLamp nextLamp() {
37 return RED;
38 }
39 };
40 public abstract TrafficLamp nextLamp();// 带抽象方法的枚举
41
42 private TrafficLamp() {// 构造方法私有化,目的是不允许程序员自己创建该类的对象。
43
44 }
45 }
1 package com.itheima;
2
3 public class Test3 {
4
5 /**
6 * 3、 方法中的内部类能不能访问方法中的局部变量,为什么?
7 * 答: 方法中的内部类可以访问方法中的局部变量,但是该局部变量必须用final关键字修饰。
8 * 因为方法中的代码是由上而下顺序执行的,方法运行结束后,局部变量就被销毁,
9 * 内部类的生命周期可能会比局部变量的生命周期长;用final修饰符修饰局部变量后,
10 * 局部变量的生命周期会延长,其不会因为语句块的结束而结束,还会长期存在。
11 * 所以方法中的内部类可以访问方法中的局部变量。 如下,示例代码所示。
12 *
13 * @author 汤柳清
14 */
15 public static void main(String[] args) {
16 Outter o = new Outter();
17 o.getInner();
18 }
19 }
20
21 class Outter {
22 public void getInner() {
23 final int a = 3; // 定义局部变量
24 class Inner { // 定义内部类Inner
25 public void show() {
26 System.out.println(a);
27 }
28 }
29 // 创建局部内部类对象
30 Inner inner = new Inner();
31 inner.show();
32 }
33
34 }
1 package com.itheima;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.util.Collections;
9 import java.util.Comparator;
10 import java.util.Set;
11 import java.util.TreeSet;
12
13 public class Test4 {
14
15 /**
16 * 4、 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
17 * 输入格式为:name,30,30,30(姓名,三门课成绩),然后把输入的学生信息按总分从高到低的顺序
18 * 写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观, 打开这个文件,就可以很清楚的看到学生的信息。
19 *
20 * @author 汤柳清
21 */
22 public static void main(String[] args) throws IOException {
23 // 自定义强制反转的比较器
24 Comparator<Student> cmp = Collections.reverseOrder();
25 //以下把比较器作为参数传递
26 Set<Student> stus = StudentInfoTool.getStudents(cmp);
27 StudentInfoTool.writeToFile(stus);
28 }
29 }
30
31 class Student implements Comparable<Student> {
32 private String name;
33 private int ma, cn, en;
34 private int sum;
35
36 Student(String name, int ma, int cn, int en) {
37 this.name = name;
38 this.ma = ma;
39 this.cn = cn;
40 this.en = en;
41 sum = ma + cn + en;
42 }
43
44 public String getName() {
45 return name;
46 }
47
48 public int getSum() {
49 return sum;
50 }
51
52 public int hashCode()// 重写方法
53 {
54 return name.hashCode() + sum * 56;// 56是随便乘的
55 }
56
57 public boolean equals(Object obj)// 重写方法
58 {
59 if (!(obj instanceof Student))
60 throw new ClassCastException("不是学生类!");
61 Student s = (Student) obj;
62 return this.name.equals(s.name) && this.sum == s.sum;
63 }
64
65 // 实现接口中的方法,分数相同再比较姓名。如果总分和姓名都相同,就是同一个人。
66 public int compareTo(Student s) {
67 int num = new Integer(this.sum).compareTo(new Integer(s.sum));
68 if (num == 0)
69 return this.name.compareTo(s.name);
70 return num;
71 }
72
73 public String toString() {
74 return "student["+name+", "+ma+", "+cn+", "+en+"]";
75 }
76 }
77
78 class StudentInfoTool {
79
80 public static Set<Student> getStudents() throws IOException// 不论带不带比较器,调用的都是带比较器的方法
81 {
82 return getStudents(null);// 不带比较器的比较
83 }
84
85 public static Set<Student> getStudents(Comparator<Student> cmp)
86 throws IOException// 带自定义比较器的比较
87 {
88 BufferedReader bufr = new BufferedReader(new InputStreamReader(
89 System.in));
90 String line = null;
91 Set<Student> stus = null;
92 if (cmp == null)// 不论带不带比较器,调用的都是掉比较器的方法
93 stus = new TreeSet<Student>();// treeset内部已经按默认自然排序,排好序啦!!!
94 else
95 stus = new TreeSet<Student>(cmp);
96 while ((line = bufr.readLine()) != null) {
97 if ("over".equals(line))// 输入over就结束
98 break;
99 String[] info = line.split(",");// 以逗号分隔输入的信息
100 Student stu = new Student(info[0], Integer.parseInt(info[1]),
101 Integer.parseInt(info[2]), Integer.parseInt(info[3]));// 字符串要转换为整形
102 stus.add(stu);
103 }
104 bufr.close();
105 return stus;
106 }
107
108 public static void writeToFile(Set<Student> stus) throws IOException {
109
110 BufferedWriter bufw = new BufferedWriter(new FileWriter("stuinfo.txt"));
111
112 for(Student stu : stus)
113 {
114 bufw.write(stu.toString()+"\t");
115 bufw.write(stu.getSum()+"");//要转换成字符串
116 bufw.newLine();
117 bufw.flush();
118 }
119
120 bufw.close();
121 }
122 }
1 package com.itheima;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class Test5 {
8
9 /**
10 * 5、 编写程序,生成5个1至10之间的随机整数,存入一个List集合,
11 * 编写方法对List集合进行排序(自定义排序算法,禁用Collections.sort方法和TreeSet),
12 * 然后遍历集合输出。
13 *
14 * @author 汤柳清
15 */
16
17 public static void main(String[] args) throws InterruptedException {
18 int[] number = new int[5];// 定义一个int数组长度为5
19 List<Integer> list = new ArrayList<Integer>();// 定义一个int数组长度为5
20 for (int i = 0; i < 5; i++) {
21 number[i] = (int) (Math.random() * 10 + 1);// 返回1~10之间的随机整数给number[i]
22 for (int j = 0; j < i; j++) {
23 if (number[i] == number[j]) {// 与之前的数对比,防止重复
24 i--;
25 break;
26 }
27 }
28 }
29 System.out.println("将随机数添加到list集合中");
30 for (int n : number) {
31 Thread.sleep(100);// 为了打印好看些
32 list.add(n);
33 System.out.print(n + " ");
34 }
35 System.out.println("\n5个1至10的随机数从小到大排序如下:");
36 Collections.sort(list);// 按升序排序
37 // 冒泡排序
38 for (int i = 0; i < list.size() - 1; i++) {
39 for (int j = 1; j < list.size() - i; j++) {
40 if ((list.get(j - 1)).compareTo(list.get(j)) > 0) { // 比较两个整数的大小
41 int temp = list.get(j - 1); // 如果J-1大于J的交换位置
42 list.set((j - 1), list.get(j));
43 list.set(j, temp);
44 }
45 }
46 }
47 // 遍历输出
48 for (int n : list) {
49 Thread.sleep(100);// 为了打印好看些
50 System.out.print(n + " ");
51 }
52 }
53 }
1 package com.itheima;
2
3 public class Test6 {
4
5 /**
6 * 6、 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、售票窗口、售票中心。
7 * 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票过程。
8 *
9 * @author 汤柳清
10 */
11 public static void main(String[] args) {
12 Test6 t = new Test6();
13 t.new Ticket();
14
15 }
16
17 class Ticket {
18 public Ticket() {
19 TicketSealCenter tsc = new TicketSealCenter(100);// 定义有100张票
20 for (int i = 0; i < 5; i++) {// 定义有5个窗口
21 new Thread(new SealWindow(i, tsc)).start();// 启动售票窗口售票
22 }
23 }
24 }
25
26 /**
27 * 售票中心类 定义了票的总数,同步售票方法
28 */
29 class TicketSealCenter {
30 int ticketNum = 50;
31 boolean flag = false; // 定义票是否卖完
32
33 public TicketSealCenter(int num) {// 定义一个改变票数的方法
34 this.ticketNum = num;
35 }
36
37 public synchronized void sellTicket(SealWindow s) {
38 if (ticketNum > 0) {//票数如果大于0
39 int n = s.num + 1;//n表示第几号窗口
40 System.out
41 .println("第--" + n + "--售票窗口卖出了第" + ticketNum + "张票!");
42 ticketNum--;//卖出一张票后减1
43 } else {
44 flag = true;
45 }
46 }
47 }
48
49 /**
50 * 售票窗口类
51 */
52 class SealWindow implements Runnable {
53 int num;//num表示第几号窗口-1,即i
54 TicketSealCenter tsc;
55
56 public SealWindow(int num, TicketSealCenter tsc) {
57 this.num = num;
58 this.tsc = tsc;
59 }
60
61 public final void run() {
62 while (!tsc.flag) {
63 tsc.sellTicket(this); // 调用售票中心类的同步票数
64 try {
65 Thread.sleep(100);
66 } catch (InterruptedException e) {
67 e.printStackTrace();
68 }
69 }
70 }
71 }
72 }
1 package com.itheima;
2
3 public class Test7 {
4
5 /**
6 * 7、 有一个类为ClassA,有一个类为ClassB,在ClassB中有一个方法b,此方法抛出异常,
7 * 在ClassA类中有一个方法a,请在这个方法中调用b,然后抛出异常。 在客户端有一个类为TestC,有一个方法为c
8 * ,请在这个方法中捕捉异常的信息。 完成这个例子,请说出java中针对异常的处理机制。
9 * 答:Java提供两种异常处理机制
10 * (1)用try...catch语句捕获并且处理异常;
11 * (2)使用throw抛出异常,异常必须是java.lang.Throwable类的对象或者该类的子类的对象;
12 * (3)使用throws声明方法抛出异常;
13 * (4)使用finally语句声明在任何情况下都会执行的代码。
14 *如下,类A和类B都是跑出了异常,而类C捕获了异常。
15 * @param 汤柳清
16 */
17 public static void main(String[] args) {
18 ClassC.methodC();
19
20 }
21 }
22
23 class ClassB {
24 public static void methodB() throws Exception {
25 System.out.println("This is methodB");
26 }
27 }
28
29 class ClassA {
30 public static void methodA() throws Exception {
31 ClassB.methodB();
32 }
33 }
34
35 class ClassC {
36 public static void methodC() {
37 try {
38 ClassA.methodA();
39 } catch (Exception e) {
40 System.out.println(e.getMessage());
41 }
42 }
43 }
1 package com.itheima;
2
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.Method;
5 /**
6 * 1
7 * 2
8 * 3
9 * @author Administrator
10 *
11 */
12 public class Test8 {
13
14 /**
15 *8、 编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。##
16 * ##分析:
17 * 1.加载类
18 * 2.加载无参构造方法
19 * 3.创建Demo对象
20 * 4.获得自定义的实例方法
21 * 5.调用showMessage方法
22 * @author 汤柳清
23 */
24 @SuppressWarnings({ "rawtypes", "unchecked" })
25 public static void main(String[] args) {
26
27 try {
28 /** 加载类*/
29 Class clazz = Class.forName("com.itheima.Demo");
30 // 加载无参构造方法
31 Constructor constructor = clazz.getConstructor();
32 // 创建Demo对象
33 Demo demo = (Demo) constructor.newInstance();
34 // 获得自定义的实例方法
35 Method method = clazz.getMethod("showMessage");
36 // 调用该方法
37 method.invoke(demo);
38 } catch (Exception e) {
39 // TODO Auto-generated catch block
40 e.printStackTrace();
41 }
42
43 }
44 }
1 package com.itheima;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6
7 public class Test9 {
8
9 /**
10 * 9、 编写一个程序,它先将键盘上输入的一个字符串转换成十进制整数, 然后打印出这个十进制整数对应的二进制形式。这个程序要考虑输入的字符串
11 * 不能转换成一个十进制整数的情况,并对转换失败的原因要区分出是数字太大,
12 * 还是其中包含有非数字字符的情况。提示:十进制数转二进制数的方式是用这个数除以2, 余数就是二进制数的最低位,接着再用得到的商作为被除数去除以2,
13 * 这次得到的余数就是次低位,如此循环,直到被除数为0为止。 其实,只要明白了打印出一个十进制数的每一位的方式
14 * (不断除以10,得到的余数就分别是个位,十位,百位),就很容易理解十进制数转二进制数的这种方式。
15 *
16 * @author 汤柳清
17 * @throws IOException
18 */
19 public static void main(String[] args) throws IOException {
20 // TODO Auto-generated method stub
21 BufferedReader bufr = new BufferedReader(new InputStreamReader(
22 System.in));
23 String line = bufr.readLine();
24 bufr.close();
25
26 ChangeToBinary(line);
27 }
28
29 public static void ChangeToBinary(String arr) {
30 char[] array = arr.toCharArray();
31 StringBuilder sb = new StringBuilder();
32 char[] number = new char[] { '0', '1', '2', '3', '4', '5', '6', '7',
33 '8', '9' };
34 for (int i = 0; i < array.length; i++) {
35 for (int j = 0; j < number.length; j++) {
36
37 if (array[i] == number[j]) {
38 continue;
39 }
40 if (j >= number.length) {
41 break;
42 }
43 }
44 }
45 double d = 0;
46 try {
47 d = Double.parseDouble(arr);
48 } catch (Exception e) {
49 throw new RuntimeException("包含有非数字字符");
50 }
51 if (d > Integer.MAX_VALUE) {
52 System.out.println("数字太大");
53 } else {
54 int data = Integer.parseInt(arr);
55
56 while (data > 0) {// 转二进制数
57
58 int b = data % 2;
59
60 sb.append(b);
61
62 data = data / 2;
63
64 }
65 }
66 System.out.println(sb.reverse());
67 }
68 }
1 package com.itheima;
2
3 /**
4 * 10:28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买多少瓶可乐?(需写出分析思路)
5 * 分析:
6 * 定义一个变量代表瓶盖数,当瓶盖数没有到3的时候,就继续购买可乐,同时瓶盖数加1,
7 * 当瓶盖数达到3,就把瓶盖数置为1,这次就不要购买可乐。
8 * 循环28次,可以使28人都能喝到可乐。
9 * 同理,50人喝可乐一样。
10 * @author 汤柳清
11 */
12 public class Test10 {
13 public static void main(String[] args) {
14 System.out.println("28人买可乐喝,需要买:" + BuyCokes(28) + "瓶");
15 System.out.println("50人买可乐喝,需要买:" + BuyCokes(50) + "瓶");
16
17 }
18
19 // 购买可乐方法
20 public static int BuyCokes(int num) {
21 // 瓶盖数
22 int bottle_cap = 0;
23 // 需要购买总瓶数
24 int sum = 0;
25 for (int i = 0; i < num; i++) {
26 if (bottle_cap != 3) {
27 // 购买一瓶
28 sum++;
29 // 同时瓶盖增加一个
30 bottle_cap++;
31 } else if (bottle_cap == 3) {
32 bottle_cap = 1;// 瓶盖数置为1
33 }
34 }
35 return sum;
36 }
37
38 }