笔试题精选
1 /** 2 * 需求: 3 * 编写函数,从一个字符串中按字节数截取一部分,但不能截取出半个中文(GBK码表) 4 * 例如:从“HM程序员”中截取2个字节是“HM”,截取4个则是“HM程”,截取3个字节也要是"HM"而不要出现半个中文 5 首先要了解中文字符有多种编码及各种编码的特征。假设n为要截取的字节数。 6 */ 7 class MyTest 8 { 9 public static void main(String[] args) throws Exception 10 { 11 String str = "HM程序员"; 12 int num = trimGBK(str.getBytes("GBK"),4); 13 System.out.println(str.substring(0,num)); 14 } 15 public static int trimGBK(byte[] buf,int n) 16 { 17 int num = 0; 18 boolean FirstHalf = false; 19 for (int i=0; i<n; i++) 20 { 21 if(buf[i]<0 && !FirstHalf) 22 { 23 FirstHalf = true; 24 }else 25 { 26 num++; 27 FirstHalf = false; 28 } 29 } 30 return num; 31 } 32 }
1 /** 2 * 需求: 3 * 定义一个交通灯枚举,包括红灯、绿灯、黄灯,需要有获得下一个灯的方法; 4 * 例如:红灯获取下一个灯是绿灯,绿灯获取下一个灯是黄灯 5 */ 6 public emun Lamp 7 { 8 RED("GREEN"),GREEN("YELLOW"),YELLOW("RED"); 9 private String next; 10 private Lamp(String next) 11 { 12 this.next = next; 13 } 14 public Lamp nextLamp() 15 { 16 return Lamp.valueOf(next); 17 } 18 }
1 import java.lang.reflect.InvocationTargetException; 2 import java.util.ArrayList; 3 import java.util.List; 4 5 public class Test03 { 6 7 /** 8 * 需求:ArrayList<Integer> list = new ArrayList<Integer>(); 9 * 在这个泛型为Integer的ArrayList中存放一个String类型的对象。 10 * 思路: 11 * 其实泛型只是给编译器使用的,ArrayList<String>与ArrayList<Integer> 12 * 在内存中完全是同一个字节码,反射可以透过编译器! 13 * 所以:必须用反射! 14 * @param args 15 */ 16 public static void main(String[] args) { 17 18 // 1、创建一个ArrayList集合,泛型限定为Integer 19 List<Integer> list = new ArrayList<Integer>(); 20 21 // 2、往集合中添加Integer类型的元素 22 list.add(1); 23 list.add(2); 24 list.add(3); 25 list.add(5); 26 list.add(8); 27 28 System.out.println(list); 29 30 // 3、反射,透过编译器往集合中添加String类型的元素 31 try { 32 list.getClass().getMethod("add", Object.class) 33 .invoke(list, "hello,itheima"); 34 } catch (IllegalAccessException | IllegalArgumentException 35 | InvocationTargetException | NoSuchMethodException 36 | SecurityException e) { 37 throw new RuntimeException("反射时发生异常"); 38 } 39 // 4、打印集合 40 System.out.println(list); 41 } 42 }
1 package com.itheima; 2 3 import java.lang.reflect.Method; 4 import java.util.ArrayList; 5 import java.util.List; 6 /* 7 题目:ArrayList<Integer> list = new ArrayList<Integer>(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象。 8 分析: 9 1.定义Integer泛型 10 2.取得list的所有方法 11 3.遍历打印list的方法 12 4.通过反射来执行list的第一个方法,第一个是list对象,代表该对象的方法,第二个是方法参数 13 步骤: 14 1.List<Integer> list = new ArrayList<Integer>(); 15 2.Method[] method=list.getClass().getMethods(); 16 3.method[i] 17 4.method[1].invoke(list, str); 18 */ 19 public class Test1 { 20 public static void main(String[] args) throws Exception { 21 List<Integer> list = new ArrayList<Integer>(); //定义Integer泛型 22 23 String str = "abc"; 24 25 Method[] method=list.getClass().getMethods();//取得list的所有方法 26 27 System.out.println(method.length); 28 29 for(int i=0;i<method.length;i++){ 30 31 System.out.println(method[i]);//遍历打印list的方法 32 33 } 34 method[1].invoke(list, str);//通过反射来执行list的第一个方法,第一个是list对象,代表该对象的方法,第二个是方法参数 35 36 System.out.println(list.size()); 37 38 for(int i=0;i<list.size();i++){ 39 40 System.out.println(list.get(i)); 41 42 } 43 } 44 45 }
1 /** 2 * 需求: 3 * ArrayList list = new ArrayList(); 4 * 在这个泛型为Integer的ArrayList中存放一个String类型的对象。 5 */ 6 import java.util.*; 7 import java.lang.*; 8 import java.lang.reflect.Method; 9 public class MyTest 10 { 11 public static void main(String[] args) throws Exception 12 { 13 ArrayList<Integer> list = new ArrayList<Integer>(); 14 Method method = list.getClass().getMethod("add",Object.class); 15 method.invoke(list,"I am a String"); 16 System.out.println(list.toString()); 17 } 18 }
1 /** 2 * 需求: 3 * 一个ArrayList对象aList中存有若干个字符串元素, 4 * 现欲遍历该ArrayList对象,删除其中所有值为"abc"的字符串元素,请用代码实现。 5 */ 6 import java.util.*; 7 public class MyTest 8 { 9 public static void main(String[] args) throws Exception 10 { 11 ArrayList<String> aList = new ArrayList<String>(); 12 aList.add("heima"); 13 aList.add("abc"); 14 aList.add("heima"); 15 aList.add("abc"); 16 aList.add("heima"); 17 aList.add("abc"); 18 System.out.println(aList.toString()); 19 Iterator<String> it = aList.iterator(); 20 while(it.hasNext()) 21 { 22 String str = it.next(); 23 if(str.equals("abc")) 24 { 25 it.remove(); 26 } 27 } 28 System.out.println(aList.toString()); 29 } 30 }
1 /** 2 * 需求: 3 * 定义一个文件输入流,调用read(byte[] b)方法 4 * 将exercise.txt文件中的所有内容打印出来(byte 数组的大小限制为5,不考虑中文编码问题)。 5 */ 6 import java.io.*; 7 public class MyTest 8 { 9 public static void main(String[] args) 10 { 11 FileInputStream fr = null; 12 try 13 { 14 fr = new FileInputStream("d:/exercise.txt"); 15 byte[] bt = new byte[5]; 16 int len = 0; 17 while((len = fr.read(bt))!=-1) 18 { 19 for (int i = 0; i<len;i++ ) 20 { 21 System.out.print((char)bt[i]); 22 } 23 } 24 } 25 catch (IOException e) 26 { 27 e.printStackTrace(); 28 }finally 29 { 30 if(fr!=null) 31 try 32 { 33 fr.close(); 34 } 35 catch (IOException e) 36 { 37 fr = null; 38 } 39 } 40 } 41 }
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 /** 4 * 需求: 5 * 编写一个程序,它先将键盘上输入的一个字符串转换成十进制整数, 6 * 然后打印出这个十进制整数对应的二进制形式。 7 * 这个程序要考虑输入的字符串不能转换成一个十进制整数的情况, 8 * 并对转换失败的原因要区分出是数字太大,还是其中包含有非数字字符的情况。 9 * @param args 10 */ 11 12 public class Test09{ 13 public static void main (String args[]) throws Exception{ 14 15 BufferedReader bufr = 16 new BufferedReader( 17 new InputStreamReader(System.in));//定义输入流 18 System.out.println("请输入需要转换的字符串:"); 19 String line = bufr.readLine();//读取输入的字符串 20 try{ 21 int i = Integer.parseInt(line);//转换为整数 22 System.out.println(i+"对应的二进制字符串是:"+Integer.toBinaryString(i));//将十进制转换为二进制 23 }catch(Exception e){ 24 String regex = ".*\\D+.*";//用正则做一下判断 25 if(line.matches(regex)) { 26 System.out.println("含有非数字字符"); 27 } else { 28 System.out.println("数字太大"); 29 } 30 } 31 } 32 }
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileWriter; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.util.Collections; 7 import java.util.Comparator; 8 import java.util.Set; 9 import java.util.TreeSet; 10 11 public class Test02 { 12 13 /** 14 * 需求: 15 * 有五个学生,每个学生有3门课(语文、数学、英语)的成绩, 16 * 写一个程序接收从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩), 17 * 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。 18 * 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。 19 * 20 * 思路: 21 * 1、通过获取键盘录入一行数据,以"over"作为结束标记,并将信息取出封装成学生对象 22 * 2、学生为对象,用集合存储,要排序,用TreeSet 23 * 3、将集合中的数据写到文件中 24 * 25 * @param args 26 */ 27 public static void main(String[] args) { 28 29 Comparator<Student> cmp = Collections.reverseOrder(); 30 31 Set<Student> stus = null; 32 try { 33 stus = StudentInfoTool.getStudents(cmp); 34 } catch (IOException e) { 35 throw new RuntimeException("键盘录入数据异常"); 36 } 37 try { 38 StudentInfoTool.write2File(stus); 39 } catch (IOException e) { 40 throw new RuntimeException("数据写入磁盘文件异常"); 41 } 42 } 43 } 44 45 // 描述学生的类,自身具备比较性,实现Comparable即可 46 class Student implements Comparable<Student> { 47 48 private String name; 49 private int chinese; 50 private int math; 51 private int english; 52 private int sum; 53 54 public Student(String name, int chinese, int math, int english) { 55 this.name = name; 56 this.chinese = chinese; 57 this.math = math; 58 this.english = english; 59 this.sum = math + chinese + english; 60 } 61 62 public String getName() { 63 return name; 64 } 65 66 public void setName(String name) { 67 this.name = name; 68 } 69 70 public int getSum() { 71 return sum; 72 } 73 74 public void setSum(int sum) { 75 this.sum = sum; 76 } 77 78 // 学生对象有可能存到HashSet或HashMap中,所以复写hashCode方法与equals方法 79 @Override 80 public int hashCode() { 81 return name.hashCode() + sum * 50; 82 } 83 84 @Override 85 public boolean equals(Object obj) { 86 if (!(obj instanceof Student)) 87 throw new ClassCastException("类型不匹配异常"); 88 Student stu = (Student) obj; 89 return this.name.equals(stu.name) && (this.sum == stu.sum); 90 } 91 92 // stu.txt文件的格式要比较直观,所以复写toString方法 93 @Override 94 public String toString() { 95 return "Student [name= " + name + ",math= " + math + ",chinese= " 96 + chinese + ", english= " + english + ", sum= " + sum + "]"; 97 } 98 99 // 存入TreeSet中,应该让元素自身具备比较性 100 @Override 101 public int compareTo(Student o) { 102 int num = this.sum - o.sum; 103 if (0 == num) 104 return this.name.compareTo(o.name); 105 return num; 106 } 107 } 108 109 class StudentInfoTool { 110 111 public static Set<Student> getStudents() throws IOException { 112 return getStudents(null); 113 } 114 115 public static Set<Student> getStudents(Comparator<Student> cmp) 116 throws IOException { 117 118 // 1、通过获取键盘录入一行数据,并将信息取出封装成学生对象 119 BufferedReader bufr = new BufferedReader(new InputStreamReader( 120 System.in)); 121 122 String line = null; 123 Set<Student> stus = null; 124 125 if (cmp == null) 126 stus = new TreeSet<Student>(); 127 else 128 stus = new TreeSet<Student>(cmp); 129 130 while ((line = bufr.readLine()) != null) { 131 if ("over".equals(line)) 132 break; 133 String[] info = line.split(","); 134 Student stu = new Student(info[0], Integer.parseInt(info[1]), 135 Integer.parseInt(info[2]), Integer.parseInt(info[3])); 136 // 2、将学生对象存到TreeSet集合中 137 stus.add(stu); 138 } 139 bufr.close(); 140 return stus; 141 } 142 143 // 3、将集合中的学生对象存到文件中 144 public static void write2File(Set<Student> stus) throws IOException { 145 146 BufferedWriter bufw = new BufferedWriter(new FileWriter("stu.txt")); 147 148 for (Student stu : stus) { 149 bufw.write(stu.toString()); 150 bufw.newLine(); 151 bufw.flush(); 152 } 153 bufw.close(); 154 } 155 }
1 package itheima.exam; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.util.ArrayList; 7 import java.util.Collections; 8 import java.util.Comparator; 9 import java.util.Iterator; 10 import java.util.List; 11 12 import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH; 13 14 public class Test05 { 15 16 /** 17 * 需求: 18 * 编写程序,循环接收用户从键盘输入多个字符串, 直到输入“end”时循环结束,并将所有已输入的字符串按字典顺序倒序打印 19 * 思路: 20 * 1、字符串本身提供的比较性为字典顺序,可以使用工具类Collections.reverse()方法将原来的比较性反序,即:字典顺序倒序 21 * 但也可以自定一个比较器,让集合自身必备比较性; 22 * 2、键盘录入的是字节流,操作的是字符流,可以使用转换流,并加入缓冲区技术,提高效率; 23 * 3、录入的字符串存储到ArrayList集合中; 24 * 4、使用Collections工具类给ArrayList中元素排序 25 * 4、打印ArrayList集合中的元素 26 * 27 * @param args 28 */ 29 public static void main(String[] args) { 30 31 // 1、定义一个ArrayList集合 32 List<String> list = new ArrayList<String>(); 33 34 // 键盘录入字符串,转换流,缓冲区 35 BufferedReader bufr = new BufferedReader(new InputStreamReader( 36 System.in)); 37 String line = null; 38 try { 39 while ((line = bufr.readLine()) != null) { 40 if ("end".equals(line)) 41 break; 42 // 往ArrayList集合中添加元素 43 list.add(line); 44 } 45 } catch (IOException e) { 46 throw new RuntimeException("IO异常"); 47 } 48 49 // 给ArrayList排序,字典倒序 50 Collections.sort(list, Collections.reverseOrder()); 51 // 打印集合 52 Iterator<String> it = list.iterator(); 53 while(it.hasNext()){ 54 System.out.println(it.next()); 55 } 56 } 57 }
1 package itheima.exam; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collection; 6 import java.util.Collections; 7 import java.util.Iterator; 8 import java.util.List; 9 import java.util.ListIterator; 10 import java.util.Random; 11 12 public class Test06 { 13 14 /** 15 * 需求: 编写程序,生成5个1至10之间的随机整数, 存入一个List集合,编写方法对List集合进行排序 16 * (自定义排序算法,禁用Collections.sort方法和TreeSet),然后遍历集合输出。 17 * 思路: 18 * 1、使用Random对象产生5个随机数 19 * 2、把这5个随机数存到ArrayList集合中 20 * 3、自定义排序算法,选择排序,冒泡排序 21 * 4、迭代器变量输出 22 * 23 * @param args 24 */ 25 public static void main(String[] args) { 26 27 List<Integer> list = new ArrayList<Integer>(); 28 29 // 1、产生5个1--10的随机数 30 Random r = new Random(); 31 for (int i = 0; i < 5; i++) { 32 Integer ii = r.nextInt(10) + 1; 33 34 // 2、添加到ArrayList集合中 35 list.add(ii); 36 } 37 38 // 3、调用自定义的排序算法 39 sort(list); 40 41 // 4、迭代器,遍历 42 Iterator<Integer> it = list.iterator(); 43 while (it.hasNext()) { 44 System.out.println(it.next()); 45 } 46 } 47 48 // 自定义的排序算法 49 private static void sort(List<Integer> list) { 50 51 Integer[] arr = list.toArray(new Integer[list.size()]); 52 selectSort(arr); 53 54 ListIterator<Integer> i = list.listIterator(); 55 for (int j = 0; j < arr.length; j++) { 56 i.next(); 57 i.set((Integer) arr[j]); 58 } 59 } 60 61 // 选择排序 62 public static void selectSort(Integer[] arr) { 63 for (int i = 0; i < arr.length - 1; i++) { 64 for (int j = i + 1; j < arr.length; j++) { 65 if (arr[i] > arr[j]) 66 swap(arr, i, j); 67 } 68 } 69 } 70 71 // 冒泡排序 72 public static void bubbleSort(Integer[] arr) { 73 for (int x = 0; x < arr.length - 1; x++) { 74 for (int y = 0; y < arr.length - x - 1; y++) { 75 if (arr[y] > arr[y + 1]) { 76 swap(arr, y, y + 1); 77 } 78 } 79 } 80 } 81 82 private static void swap(Integer[] arr, int i, int j) { 83 Integer temp = arr[i]; 84 arr[i] = arr[j]; 85 arr[j] = temp; 86 } 87 }
1 package itheima.exam; 2 3 import java.io.BufferedReader; 4 import java.io.FileNotFoundException; 5 import java.io.FileReader; 6 import java.io.FileWriter; 7 import java.io.IOException; 8 import java.util.Arrays; 9 10 public class Test07 { 11 12 /** 13 * 需求: 14 * 已知文件a.txt文件中的内容为“bcdeadferwplkou”, 15 * 请编写程序读取该文件内容,并按照自然顺序排序后输出到b.txt文件中。 16 * 即b.txt中的文件内容应为“abcd…………..”这样的顺序。 17 * 思路: 18 * 1、用一个字符读取流读取a.txt中的内容,用String对象存储 19 * 2、Sting-->char[],调用Arrays工具类的排序功能,也可以自定义排序功能, 20 * 但在开发中,一般不干这种事! 21 * 3、用一个字符写出流把排好序的字符串写到b.txt文件中 22 * 23 * @param args 24 * @throws IOException 25 */ 26 public static void main(String[] args) { 27 28 // 1、读取流与a.txt相关联 29 FileReader fr =null; 30 try { 31 fr = new FileReader("a.txt"); 32 } catch (FileNotFoundException e) { 33 throw new RuntimeException("找不到指定的文件"); 34 } 35 BufferedReader bufr = new BufferedReader(fr); 36 // 2、读取 37 String str =null; 38 try { 39 str = bufr.readLine(); 40 } catch (IOException e) { 41 throw new RuntimeException("读取文件异常"); 42 } 43 // 3、用完了流,及时关闭 44 try { 45 if(bufr!=null) 46 bufr.close(); 47 } catch (IOException e) { 48 throw new RuntimeException("读取流关闭失败"); 49 } 50 // 4、字符串转成字符数组 51 char[] arr = str.toCharArray(); 52 // 5、对字符数组进行排序 53 Arrays.sort(arr); 54 55 // System.out.println(arr); 56 57 FileWriter fw =null; 58 try { 59 fw = new FileWriter("b.txt"); 60 } catch (IOException e) { 61 throw new RuntimeException("创建文件失败"); 62 } 63 // 6、把排好序的数据写到指定的文件中 64 try { 65 fw.write(arr); 66 } catch (IOException e) { 67 throw new RuntimeException("数据写入磁盘文件异常"); 68 } 69 // 7、关闭流 70 try { 71 if(null !=fw) 72 fw.close(); 73 } catch (IOException e) { 74 throw new RuntimeException("写出流关闭失败"); 75 } 76 } 77 }
1 package itheima.exam; 2 3 public class Test08 { 4 5 /** 6 * 需求: 7 * 将字符串中进行反转。abcde --> edcba 8 * 思路: 9 * 1、字符串转为字符数组 10 * 2、对字符数组进行反转,并返回字符串 11 * 12 * @param args 13 */ 14 public static void main(String[] args) { 15 16 String str = "abcde"; 17 18 str = reverse(str); 19 20 System.out.println(str); 21 } 22 23 // 反转字符串的方法 24 private static String reverse(String str) { 25 26 // 1、字符串转成字符数组 27 char[] arr = str.toCharArray(); 28 29 // 2、对字符数组进行反转 30 for (int start = 0, end = arr.length - 1; start <= end; start++, end--) { 31 swap(arr, start, end); 32 } 33 // 3、返回字符串 34 return new String(arr); 35 } 36 // 功能抽取,提高复用性 37 private static void swap(char[] arr, int start, int end) { 38 char temp = arr[start]; 39 arr[start] = arr[end]; 40 arr[end] = temp; 41 } 42 }
1 package itheima.exam; 2 3 public class Test09 { 4 5 /** 6 * 需求: 7 * 在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符, 8 * 如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),否则,返回-1。 9 * 要搜索的字符数组和字符都以参数形式传递传递给该方法,如果传入的数组为null,应抛出IllegalArgumentException异常。 10 * 在类的main方法中以各种可能出现的情况测试验证该方法编写得是否正确, 例如,字符不存在,字符存在,传入的数组为null等。 11 * 思路: 12 * 其实这有点象String对象中的indexOf方法, 13 * 那么可以将字符数组转成String对象,底层封装String的indexOf方法 14 * 也可以自定义具体的实现 15 * 16 * @param args 17 */ 18 public static void main(String[] args) { 19 20 String str = "hello,itheima"; 21 char[] arr = str.toCharArray(); 22 char[] arr1 = null; 23 24 System.out.println("myIndexOf_1::" + myIndexOf_1(arr, 'h')); 25 System.out.println("myIndexOf_1::" + myIndexOf_1(arr, 'i')); 26 System.out.println("myIndexOf_1::" + myIndexOf_1(arr, '5')); 27 28 // System.out.println("myIndexOf_1::"+myIndexOf_1(arr1,'1')); 29 30 System.out.println("myIndexOf_2::" + myIndexOf_2(arr, 'h')); 31 System.out.println("myIndexOf_2::" + myIndexOf_2(arr, 'i')); 32 System.out.println("myIndexOf_2::" + myIndexOf_2(arr, '5')); 33 34 // System.out.println("myIndexOf_2::"+myIndexOf_2(arr1,'1')); 35 } 36 37 // 方式一 38 public static int myIndexOf_1(char[] arr, char ch) { 39 40 if(arr == null) 41 throw new IllegalArgumentException("字符数组不能为null!"); 42 43 String str = new String(arr); 44 return str.indexOf(ch); 45 } 46 47 // 方式二 48 public static int myIndexOf_2(char[] arr, char ch) { 49 50 if(arr == null) 51 throw new IllegalArgumentException("字符数组不能为null!"); 52 53 for(int i = 0; i < arr.length; i++) 54 if(ch == arr[i]) 55 return i; 56 return -1; 57 } 58 }
1 package itheima.exam; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 7 public class Test10 { 8 9 /** 10 * 需求: 11 * 10、金额转换,阿拉伯数字转换成中国传统形式。 例如:101000001010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整 12 * 分析: 13 * 我们都知道:英文的数字读法是按照三位为一个大单位的;中文的数字读法是四位为一个大单位的:万、亿 14 * 例如:"1010 0001 1010":一千零一十亿零一万一千零一十元; 15 * 可以看出: 16 * 1、满四位,则加上一个大单位; 17 * 2、当连续几个零时,只读出一个零 18 * 思路: 19 * 1、键盘录入表示金额的阿拉伯数字形式的字符串 20 * 2、使用正则表达式进行检验,不符合规则,重新录入 21 * 3、将阿拉伯数字转成传统的中文读取形式,用到数组查表法,比较简单 22 * 23 * @param args 24 */ 25 public static void main(String[] args) { 26 27 String money = null; 28 // 1、键盘录入数据 29 try { 30 money = getArabNumber(); 31 } catch (IOException e) { 32 throw new RuntimeException("键盘录入失败,请重启程序"); 33 } 34 // 2、转成传统的中文读法 35 System.out.println(ChangeToChinenseNumber(money)); 36 } 37 38 // 键盘录入数据 单独封装成函数 39 public static String getArabNumber() throws IOException { 40 41 BufferedReader bufr = new BufferedReader(new InputStreamReader( 42 System.in)); 43 String line = null; 44 System.out.println("请录入一个1到12位数的金额:"); 45 while (true) { 46 line = bufr.readLine(); 47 // 正则判断 48 if (line.matches("[1-9][0-9]{1,11}")) 49 return line; 50 else 51 System.out.println("您好,您录入的数据不符,请重新录入:"); 52 continue; 53 } 54 } 55 56 // 转成传统的中文形式 57 public static String ChangeToChinenseNumber(String money) { 58 59 char[] ArabNumber = new char[] { '0', '1', '2', '3', '4', '5', '6', 60 '7', '8', '9' }; 61 char[] ChineseNumber = new char[] { '零', '壹', '贰', '叁', '肆', '伍', '陆', 62 '柒', '捌', '玖', }; 63 64 // 先将阿拉伯数字转成大写中文 65 for (int i = 0; i < ArabNumber.length; i++) 66 money = money.replace(ArabNumber[i], ChineseNumber[i]); 67 System.out.println(money); 68 69 // 单位,后三位为大单位;前三位为小单位 70 char[] numberUnit = new char[] { '仟', ' ', '拾', '佰', '圆', '万', '亿' }; 71 72 // 大家都知道,中文的数字是按四位为一个大单位的:圆,万,亿 73 // shang代表大单位,yushu代表小单位 74 int shang; 75 int yushu; 76 77 // 用一个容器存储 78 StringBuilder sb = new StringBuilder(); 79 80 for (int length = money.length(), index = 0; length > 0; length--, index++) { 81 shang = length / 4; 82 yushu = length % 4; 83 // 为'零'时,单独处理 84 if (money.charAt(index) == '零') { 85 // 余数为1,这时正是个位、万位、亿位的情况 86 if (yushu == 1) { 87 if (!(shang != 2 && money.substring(index - 3, index + 1) 88 .equals("零零零零"))) { 89 // 大单位上的四位数不全为'零',加上大单位:圆、万、亿 90 sb.append(numberUnit[4 + shang]); 91 } 92 } else { 93 // 否则,暂时不加 94 } 95 continue; 96 } 97 98 // 前面已经处理了数字为'零'的情况,当数字不为零,且前面一位为零时,应该额外加上一个'零'字 99 if (length != money.length() && yushu != 0 100 && money.charAt(index - 1) == '零') { 101 sb.append('零'); 102 } 103 104 // 普通情况,先添加数字,然后添加单位 105 sb.append(money.charAt(index)); 106 if (yushu == 1) { 107 sb.append(numberUnit[4 + shang]); 108 } else { 109 sb.append(numberUnit[yushu]); 110 } 111 } 112 // 最后,往容器中添加一个'整'字 113 sb.append("整"); 114 return sb.toString(); 115 } 116 }
1 package com.itheima; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 /** 9 * 1、编写一个类,在main方法中定义一个Map对象(采用泛型),加入若干个对象, 10 * 然后遍历并打印出各元素的key和value。 11 * @author fujianguo 12 */ 13 public class Test01 { 14 15 public static void main(String[] args) { 16 //创建Map对象 17 Map<String,Integer> map = new HashMap<String,Integer>(); 18 //加入若干对象 19 map.put("zhangsan", 13); 20 map.put("wangwu", 33); 21 map.put("zhouxingxing", 22); 22 map.put("lizi", 25); 23 //遍历Map对象 24 Set<Map.Entry<String,Integer>> set = map.entrySet(); 25 Iterator<Map.Entry<String,Integer>> it = set.iterator(); 26 while(it.hasNext()){ 27 Map.Entry<String,Integer> me = it.next(); 28 //打印元素key和value 29 System.out.println("key:"+me.getKey()+" value:"+me.getValue()); 30 } 31 } 32 33 }
1 package com.itheima; 2 3 import java.lang.reflect.Field; 4 5 /** 6 * 2、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value. 7 * @author fujianguo 8 */ 9 public class Test02 { 10 11 public static void main(String[] args) { 12 //创建学生类对象 13 Student s = new Student("zhansan",88,97,87); 14 System.out.println(s); 15 Test02 test = new Test02(); 16 //调用此方法设置name值为wangwu 17 test.setProperty(s, "name", "wangwu"); 18 System.out.println("重新设值后:"); 19 System.out.println(s); 20 } 21 //定义可将obj对象中名为propertyName的属性的值设置为value 22 public void setProperty(Object obj, String propertyName, Object value){ 23 try { 24 //反射 获得obj对象字节码类 25 Class clazz = obj.getClass(); 26 //获得obj对象的实例变量 27 Field field = clazz.getDeclaredField(propertyName); 28 //暴力反射 29 field.setAccessible(true); 30 //将obj对象中名为propertyName的属性的值设置为value 31 field.set(obj, value); 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } 35 } 36 37 }
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.Comparator; 9 import java.util.Set; 10 import java.util.TreeSet; 11 12 /** 13 * 4、 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息, 14 * 输入格式为:name,30,30,30(姓名,三门课成绩), 15 * 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。 16 * 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。 17 * @author fujianguo 18 */ 19 public class Test04 { 20 21 public static void main(String[] args){ 22 //从键盘输入学生信息 23 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 24 //定义装学生信息的TreeSet集合,定义比较器使学生按总分从高到低排序 25 Set<Student> set = new TreeSet<Student>(new Comparator<Student>() { 26 @Override 27 public int compare(Student o1, Student o2) { 28 return new Integer(o2.getTotal()).compareTo(o1.getTotal()); 29 } 30 }); 31 String line = null; 32 System.out.println("输入学生信息(格式:name,30,30,30(姓名,语文,数学,英语)):"); 33 try { 34 for(int i=0;i<5;i++){ 35 //读取数据 36 line = br.readLine().trim(); 37 //将字符串进行切割 38 String[] infos = line.split(","); 39 //创建学生实例对象 40 Student stu = null; 41 try { 42 stu = new Student(infos[0],Integer.parseInt(infos[1]), 43 Integer.parseInt(infos[2]), 44 Integer.parseInt(infos[3])); 45 } catch (NumberFormatException e) { 46 throw new RuntimeException("学生信息输入格式有误。"); 47 } 48 set.add(stu); 49 } 50 System.out.println("输入完毕"); 51 //调用存储学生信息的方法 52 storeFile(set); 53 } catch (IOException e) { 54 e.printStackTrace(); 55 }finally{ 56 if(br!=null){ 57 try { 58 br.close(); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 } 64 } 65 //定义存储学生信息到stu.txt文件中 66 public static void storeFile(Set<Student> set){ 67 BufferedWriter bw = null; 68 try { 69 //创建写入流,将数据写入D:\stu.txt文件中 70 bw = new BufferedWriter(new FileWriter("D:\\stu.txt")); 71 //循环写入 72 for(Student s:set){ 73 bw.write(s.toString()+"\r\n"); 74 bw.flush(); 75 } 76 } catch (IOException e) { 77 e.printStackTrace(); 78 }finally{ 79 if(bw!=null){ 80 try { 81 //关闭流 82 bw.close(); 83 } catch (IOException e) { 84 e.printStackTrace(); 85 } 86 } 87 } 88 } 89 90 }
1 package com.itheima; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 import java.util.Arrays; 10 11 /** 12 * 5、 已知文件a.txt文件中的内容为“bcdeadferwplkou”,请编写程序读取该文件内容, 13 * 并按照自然顺序排序后输出到b.txt文件中。即b.txt中的文件内容应为“abcd…………..”这样的顺序。 14 * @author fujianguo 15 */ 16 public class Test05 { 17 18 public static void main(String[] args){ 19 BufferedReader br = null; 20 BufferedWriter bw = null; 21 try { 22 //定义读取a.txt的流对象 23 br = new BufferedReader(new FileReader("F:\\a.txt")); 24 //定义输入流 25 bw = new BufferedWriter(new FileWriter("F:\\b.txt")); 26 //读取数据-bcdeadferwplkou 27 String line = br.readLine().trim(); 28 29 //将字符串变成字节数组 30 char[] chs = line.toCharArray(); 31 //将数组排序 32 Arrays.sort(chs); 33 //将排序后的数据写入文件中-abcddeefklopruw 34 bw.write(new String(chs)); 35 36 } catch (IOException e) { 37 e.printStackTrace(); 38 }finally{ 39 if(bw!=null){ 40 //关闭输入流同时刷新数据到文件b.txt中 41 try { 42 bw.close(); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } 46 } 47 if(br!=null){ 48 //关闭读取流 49 try { 50 br.close(); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 } 56 } 57 58 }
1 package com.itheima; 2 3 import java.util.HashSet; 4 import java.util.Random; 5 import java.util.Set; 6 7 /** 8 * 6、 编写一个程序,获取10个1至20的随机数,要求随机数不能重复。 9 * @author fujianguo 10 */ 11 public class Test06 { 12 13 public static void main(String[] args) { 14 //调用生产随机数的方法 15 int[] arr = newRandom(); 16 //打印数组 17 printArr(arr); 18 } 19 //定义生成不能重复随机数的方法-效率更高 20 public static int[] newRandom(){ 21 final int len = 10; 22 Random rand = new Random(); 23 int[] arr = new int[len]; 24 //遍历数组,添加随机数 25 for(int i=0;i<len;i++){ 26 //产生随机数 27 int r = rand.nextInt(20)+1; 28 //定义是否重复标记,如果重复则为真。 29 boolean flag = false; 30 //循环检测新生产的随机数,直到随机数不重复为止 31 do{ 32 //假设随机数不重复 33 flag = false; 34 //循环检查是否重复 35 for(int j=0;j<i;j++){ 36 //如果重复 37 if(arr[j]==r){ 38 //标记为真,表示重新生成随机数 39 flag = true; 40 r = rand.nextInt(20)+1; 41 break; 42 } 43 } 44 }while(flag); 45 //为数组添加新元素 46 arr[i] = r; 47 } 48 return arr; 49 } 50 //定义生成不能重复随机数的方法-效率低 51 public static void newRandom2(){ 52 //定义随机数生成器。 53 Random random = new Random(); 54 //定义不能添加重复元素的HashSet类 55 Set<Integer> set = new HashSet<Integer>(); 56 while(true){ 57 int num = random.nextInt(20)+1; 58 set.add(num); 59 if(set.size()==10){ 60 break; 61 } 62 } 63 System.out.println(set); 64 } 65 //遍历数组 66 public static void printArr(int[] arr){ 67 System.out.print("["); 68 for(int i=0;i<arr.length;i++){ 69 if(i!=arr.length-1){ 70 System.out.print(arr[i]+","); 71 }else{ 72 System.out.println(arr[i]+"]"); 73 } 74 } 75 } 76 }
1 package com.itheima; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Iterator; 6 import java.util.List; 7 import java.util.Random; 8 9 /** 10 * 8、 编写程序,生成5个1至10之间的随机整数,存入一个List集合, 11 * 编写方法对List集合进行排序(自定义排序算法,禁用Collections.sort方法和TreeSet),然后遍历集合输出。 12 * @author fujianguo 13 */ 14 public class Test08 { 15 16 public static void main(String[] args) { 17 List<Integer> list = new ArrayList<Integer>(); 18 Random r = new Random(); 19 for(int i=0;i<5;i++){ 20 list.add(r.nextInt(10)+1); 21 } 22 System.out.println("排序前:"+list); 23 //调用自定义的排序算法 24 list = mySort(list); 25 System.out.print("排序后:"); 26 //迭代集合 27 Iterator<Integer> it = list.iterator(); 28 while(it.hasNext()){ 29 System.out.print(it.next()+","); 30 } 31 32 } 33 //自定义排序方法 34 public static List<Integer> mySort(List<Integer> list){ 35 //定义刚好的Integer数组,避免传入null值 36 Integer[] arr = new Integer[list.size()]; 37 //将集合变成数组 38 arr = list.toArray(arr); 39 //对数组进行排序 40 mpSort(arr); 41 //printArr(arr); 42 //将排序后的数组变成集合 43 list = Arrays.asList(arr); 44 return list; 45 } 46 //数组冒泡排序 47 public static void mpSort(Integer[] arr){ 48 for(int i=0;i<arr.length;i++){ 49 for(int j=0;j<arr.length-i-1;j++){ 50 if(arr[j]>arr[j+1]){ 51 int temp = arr[j]; 52 arr[j] = arr[j+1]; 53 arr[j+1] = temp; 54 } 55 } 56 } 57 } 58 //遍历数组 59 public static void printArr(Integer[] arr){ 60 System.out.print("["); 61 for(int i=0;i<arr.length;i++){ 62 if(i!=arr.length-1){ 63 System.out.print(arr[i]+","); 64 }else{ 65 System.out.println(arr[i]+"]"); 66 } 67 } 68 } 69 }
1 package com.itheima; 2 3 /** 4 * 9、 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 5 * 如: n = 4 则打印 6 * 1 2 3 4 7 * 12 13 14 5 8 * 11 16 15 6 9 * 10 9 8 7 10 * @author fujianguo 11 */ 12 public class Test09 { 13 14 // 15 public static void main(String[] args) { 16 //调用打印从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列的二维数组方法 17 arrPrint(4); 18 } 19 //打印从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列的二维数组 20 public static void arrPrint(int num){ 21 //定义定长二维数组 22 int[][] arr = new int[num][num]; 23 int n = arr.length; 24 int count = 0; 25 int max = 0; 26 //递归为二维数组赋值 27 rec2DArr(arr,n,count,max); 28 //打印 29 print2DArr(arr); 30 } 31 /** 32 * 递归为二维数组赋值 33 * @param arr 二维数组 34 * @param n 控制递归次数 35 * @param count 计算圈数 最外圈为0 36 * @param max 开始循环值 37 */ 38 public static void rec2DArr(int[][] arr,int n,int count,int max){ 39 //递归控制条件 40 if(n>0){ 41 //纵坐标控制值 42 int k = 0; 43 //(n-1)*4代表每一圈的数值范围 44 for(int i=0;i<(n-1)*4;i++){ 45 //在上边赋值 46 if(i<n-1){ 47 arr[count+0][count+i] = ++max; 48 } 49 //向右边赋值 50 else if(i<2*n-2){ 51 arr[count+k++][arr.length-1-count]=++max; 52 } 53 //在下边赋值 54 else if(i<3*n-3){ 55 arr[arr.length-1-count][(k--)+count]=++max; 56 } 57 //向左边赋值 58 else if(i<4*n-4){ 59 arr[arr.length-1-(k++)-count][0+count]=++max; 60 } 61 } 62 //当n为奇数时,存在n=1的情况,最里圈只有一个数 63 if(n==1){ 64 arr[arr.length/2][arr.length/2]=max+1; 65 } 66 //增加圈数 67 count++; 68 //边界每次减少两个数值 69 n -= 2; 70 //递归 71 rec2DArr(arr,n,count,max); 72 } 73 } 74 //打印二维数组 75 public static void print2DArr(int[][] arr){ 76 //二维数组需要双重循环打印 77 for(int[] ar : arr){ 78 for(int a : ar){ 79 if(a<10) 80 System.out.print(" "+a+" "); 81 else 82 System.out.print(a+" "); 83 } 84 System.out.println(); 85 } 86 } 87 88 }
1 package com.itheima; 2 /** 3 * 10、28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝? 4 * 假如是50人,又需要买多少瓶可乐?(需写出分析思路) 5 * @author fujianguo 6 */ 7 public class Test10 { 8 9 /* 10 分析:从题意可知:当拿3个瓶盖去换一瓶可乐,多了一瓶可乐同时又多了一个瓶盖, 11 再买两瓶可乐,换取一瓶可乐同时多了一个瓶盖,循环..直到够所有人喝到可乐为止。 12 */ 13 public static void main(String[] args) { 14 //如果28人购买可乐 15 int buyNum = countCokes(28); 16 System.out.println("28人购买可乐,需要购买:"+buyNum+"瓶!"); 17 //如果50人购买可乐 18 int buyNum2 = countCokes(50); 19 System.out.println("50人购买可乐,需要购买:"+buyNum2+"瓶!"); 20 } 21 //购买可乐方法 22 public static int countCokes(int people){ 23 //瓶盖数 24 int cap = 0; 25 //需要购买瓶数 26 int sum = 0; 27 for(int i=0;i<people;i++){ 28 if(cap!=3){ 29 //购买一瓶 30 sum++; 31 //同时瓶盖增加一个 32 cap++; 33 } 34 else if(cap==3){ 35 cap = 1; 36 } 37 } 38 return sum; 39 } 40 41 }
1 package com.itheima; 2 /** 3 * 10、 金额转换,阿拉伯数字转换成中国传统形式。 4 * 例如:1010 0000 1010 5 * 转换为 壹仟零壹拾亿零壹仟零壹拾圆整 6 * @author Administrator 7 * 8 */ 9 public class Test10 { 10 11 /** 12 * @param args 13 */ 14 public static void main(String[] args) { 15 16 String str = "101000001010"; 17 convertToChineseFormat(str); 18 } 19 /** 20 * 将字符串转换为中文格式 21 * @param str 22 */ 23 public static void convertToChineseFormat(String str){ 24 if(!str.matches("\\d+")){//正则判断是不是数字 25 System.out.println("字符串" + str + "不是数字格式,无法转换!"); 26 return;//不是 则返回 27 } 28 while(str.startsWith("0")){ //将字符串最前面的0去掉 29 str = str.substring(1, str.length()); 30 } 31 char[] num = new char[]{'0','1','2','3','4','5','6','7','8','9'}; 32 char[] cnNum = new char[]{'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'}; 33 for(int i=0; i<10; i++){//将字符串数字替换成中文数字,循环对应替换 34 str = str.replace(num[i], cnNum[i]); 35 } 36 37 StringBuilder sb = new StringBuilder(str);//StringBuilder存放字符串,用于插入删除操作 38 int index = str.length()-1; //从第index个字符从后往前开始操作,操作一次,index-- 39 //存放金额单位 40 String[] unit = {"","拾","佰","仟"}; 41 String[] unit4 = {"万","亿"}; 42 43 boolean flag = false;//判断前一个数是否为零的标记 44 45 for(int i=0; i<str.length(); i++){//循环体内对sb进行操作 46 47 //每4位插入万每8位插入亿,最低位先不设置单位 48 if(i%4 == 0 && i != 0){ 49 //根据金额规则,单位万前面为4个零时,不插入万,并将index位置(最低位)的零删除 50 if((i/4-1)%2 == 0 && index >= 3 && str.substring(index-3, index+1).equals("零零零零")){ 51 sb.deleteCharAt(index); 52 index--; 53 continue; 54 } 55 //否则在index+1位置插入相应的单位:万、亿 56 sb.insert(index+1, unit4[(i/4-1)%2]); 57 } 58 //如果4位的最低位为零,删除最低位的零,将零标志置为true 59 if(i%4 == 0 && str.charAt(index) == '零'){ 60 sb.deleteCharAt(index); 61 flag = true; 62 index--; 63 continue; 64 } 65 //如果前一位为零并且这一位也为零,删除这一位的零 66 if(flag && str.charAt(index) == '零'){ 67 sb.deleteCharAt(index); 68 index--; 69 continue; 70 } 71 //如果当前位为零,将零标志置为true 72 if(str.charAt(index) == '零'){ 73 flag = true; 74 index--; 75 continue; 76 } 77 //当前位不为零,将零标志位置为false,插入金额单位 78 flag = false; 79 sb.insert(index+1, unit[i%4]); 80 index--; 81 } 82 //完善金额表示形式 83 sb.append("圆整"); 84 System.out.println(sb.toString()); 85 } 86 87 }
1 package com.itheima; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InputStreamReader; 8 import java.io.OutputStream; 9 import java.io.OutputStreamWriter; 10 11 /** 12 * 7、 定义一个文件输入流,调用read(byte[] b) 方法将exercise.txt文件中的 所有内容打印出来(byte数组的大小限制为5)。 13 * 14 * @author Administrator 15 * 16 */ 17 public class Test7 { 18 public static void main(String[] args) { 19 InputStream input = null;// 准备一个字节输入流对象 20 try { 21 input = new FileInputStream("src\\com\\itheima\\exercise.txt");// 实例一个输入流对象 22 OutputStream out = System.out;// 得到输出流对象,控制台 23 24 byte[] b = new byte[5];// 定义缓冲数组 25 int len = 0;// 读取的字节数 26 27 try { 28 while ((len = input.read(b)) != -1) { 29 out.write(b, 0, len);// 写入到流中,控制台 30 31 } 32 33 } catch (FileNotFoundException e) { 34 System.out.println("文件不存在"); 35 } 36 37 } catch (IOException e) { 38 39 System.out.println("文件读取失败"); 40 41 } finally { 42 try { 43 input.close(); 44 45 } catch (IOException e) { 46 System.out.println("关闭输入流失败"); 47 } 48 } 49 } 50 }
1 package com.itheima; 2 3 /** 4 * 8、 将字符串中进行反转。abcde --> edcba 5 * 6 * @author Administrator 7 * 8 */ 9 public class Test8 { 10 public static void main(String[] args) { 11 String str = reverseString("abcde");// 接受反转的字符串 12 System.out.println(str);// 打印输出 13 } 14 15 /** 16 * 反转字符串的方法 17 * 18 * @param str 19 * @return 20 */ 21 public static String reverseString(String str) { 22 char[] chs = str.toCharArray();// 将字符串变为字符数组 23 // 循环遍历,开始指针自加,末尾指针自减 24 for (int start = 0, end = chs.length - 1; start < end; start++, end--) { 25 // 交换位置 26 char temp = chs[start]; 27 chs[start] = chs[end]; 28 chs[end] = temp; 29 } 30 return new String(chs);// 重新把数组变为字符串 31 } 32 }
1 package com.itheima; 2 3 /** 4 * 8、 将字符串中进行反转。abcde --> edcba 5 * 6 * @author Administrator 7 * 8 */ 9 public class Test8 { 10 public static void main(String[] args) { 11 String str = reverseString("abcde");// 接受反转的字符串 12 System.out.println(str);// 打印输出 13 } 14 15 /** 16 * 反转字符串的方法 17 * 18 * @param str 19 * @return 20 */ 21 public static String reverseString(String str) { 22 char[] chs = str.toCharArray();// 将字符串变为字符数组 23 // 循环遍历,开始指针自加,末尾指针自减 24 for (int start = 0, end = chs.length - 1; start < end; start++, end--) { 25 // 交换位置 26 char temp = chs[start]; 27 chs[start] = chs[end]; 28 chs[end] = temp; 29 } 30 return new String(chs);// 重新把数组变为字符串 31 } 32 }
1 package com.itheima; 2 3 import java.util.Arrays; 4 import java.util.Scanner; 5 6 public class Test10 { 7 /** 8 * 10、 有100个人围成一个圈,从1开始报数, 报到14的这个人就要退出。 然后其他人重新开始, 9 * 从1报数,到14退出。问:最后剩下的是100人中的第几个人? 10 */ 11 private static int count = 0;// 定义出局的编号,默认从0开始 12 13 public static void main(String[] args) { 14 Scanner scanner = new Scanner(System.in);// 键盘录入 15 System.out.println("请输入人数:"); 16 int totalPerson = scanner.nextInt();// 总人数 17 System.out.println("请输入第几个人要退出:"); 18 int outNum = scanner.nextInt();// 第几个人要退出。 19 judgePerson(totalPerson, outNum);// 调用判断人数的方法 20 } 21 22 /** 23 * 对人数进行判断 24 * 25 * @param totalPerson 26 * @param outNum 27 */ 28 private static void judgePerson(int totalPerson, int outNum) { 29 if (totalPerson == 1) {// 如果总人数是1,退出的就是这个人。 30 System.out.println("最后剩下的人为" + totalPerson + "个"); 31 32 } else {// 否则调用退出的方法 33 personExit(totalPerson, outNum); 34 } 35 } 36 37 /** 38 * 退出方法 39 * 40 * @param totalPerson 41 * 总人数 42 * @param outNum 43 * 第几个人要退出 44 */ 45 private static void personExit(int totalPerson, int outNum) { 46 int[] arr = new int[totalPerson];// 实例一个数组,长度为总人数 47 for (int j = 0; j < totalPerson; j++) {// 循环遍历 48 for (int i = 0; i < outNum; i++) { 49 count++;// 每数一个人,则编号加1 50 if (j > 0) {// 这里j>0可以不用判断,因为上面已经判断过了。 51 measure(j, arr);// 调用判断count是否存在的方法 52 } 53 if (count > totalPerson) { 54 count = 1;// 若count大于总人重新赋值为1 55 measure(j, arr);// 调用判断count是否存在的方法。 56 } 57 } 58 arr[j] = count;// 将退出的人保存到数组中. 59 } 60 System.out.println("退出的顺序为:" + Arrays.toString(arr)); 61 System.out.println("最后剩下的人为:" + arr[totalPerson - 1]);// 最后剩下的人 62 } 63 64 /** 65 * 判断count是不是存在 66 * 67 * @param n 68 * @param arr 69 */ 70 private static void measure(int n, int[] arr) { 71 // 双重循环判断,因为要保证count的唯一。 72 for (int s = 0; s < n; s++) { 73 for (int w = 0; w < n; w++) { 74 if (count == arr[w]) 75 count++;// 若存在则加1. 76 } 77 } 78 } 79 }
1 import java.lang.reflect.Method; 2 3 public class Test08 { 4 5 /** 6 * 需求: 7 * 编写一个类,增加一个实例方法用于打印一条字符串。 8 * 并使用反射手段创建该类的对象, 并调用该对象中的方法。 9 * @param args 10 */ 11 @SuppressWarnings("unchecked") 12 public static void main(String[] args) throws Exception 13 { 14 15 //通过反射获得TestPrint类的字节码 16 Class<TestPrint> Clazz = (Class<TestPrint>) Class.forName("com.itheima.TestPrint"); 17 //通过字节码获得TestPrint类的方法 18 Method methodPrint = Clazz.getMethod("print", String.class); 19 //把通过反射创建该类对象,将打印内容传递给invoke方法 20 methodPrint.invoke(Clazz.newInstance(),"print test"); 21 22 } 23 24 } 25 26 class TestPrint 27 { 28 public static void print(String s) 29 { 30 System.out.println(s); 31 } 32 }
1 package com.itheima; 2 import java.beans.PropertyDescriptor; 3 import java.lang.reflect.Method; 4 5 /*1、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value. 6 public void setProperty(Object obj, String propertyName, Object value){ 7 }*/ 8 public class Test01 { 9 public void setProperty(Object obj, String propertyName, Object value) throws Exception{ 10 PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass()); 11 Method change = pd.getWriteMethod();//取得用于写入属性值的方法 12 change.invoke(obj, value); //invoke调用change的写入属性值方法,将value传入方法 13 } 14 public static void main (String []args) throws Exception{ 15 Test01 setPN2V = new Test01(); 16 Person p = new Person(); 17 String before1 = p.getName(); 18 setPN2V.setProperty(p, "name", "heima"); 19 System.out.println("改变之前的名字是:"+before1+"\r改变后的名字是:"+p.getName()); 20 String before2 = p.getAihao(); 21 setPN2V.setProperty(p, "aihao", "basketball"); 22 System.out.println("改变之前的爱好是:"+before2+"\r改变后的爱好是:"+p.getAihao()); 23 } 24 25 } 26 //定义一个Person类 27 class Person{ 28 private String name="bushijie"; 29 private String aihao="football"; 30 public void setName(String name){ 31 this.name = name; 32 } 33 public String getName(){ 34 return this.name; 35 } 36 public String getAihao() { 37 return aihao; 38 } 39 public void setAihao(String aihao) { 40 this.aihao = aihao; 41 } 42 } 43 /*运行结果如下: 44 改变之前的名字是:bushijie 45 改变后的名字是:heima 46 改变之前的爱好是:football 47 改变后的爱好是:basketball 48 */
1 package com.itheima; 2 3 4 /*3、 假如我们在开发一个系统时需要对员工进行建模,员工包含 3 个属性:姓名、工号以及工资。 5 经理也是员工,除了含有员工的属性外,另为还有一个奖金属性。 6 请使用继承的思想设计出员工类和经理类。要求类中提供必要的方法进行属性访问。*/ 7 public class Test03 { 8 /* 分析: 员工类中有属性:姓名、工号以及工资并且有getter和setter方法。经理类继承了员工类并添加了奖金属性*/ 9 class Employee { 10 private String name; 11 private String id; 12 private double wages; 13 Employee(String name, String id, double wages) { 14 this.name = name; 15 this.id = id; 16 this.wages = wages; 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public String getId() { 28 return id; 29 } 30 31 public void setId(String id) { 32 this.id = id; 33 } 34 35 public double getWages() { 36 return wages; 37 } 38 39 public void setWages(double wages) { 40 this.wages = wages; 41 } 42 } 43 //经理类 44 class Manager extends Employee { 45 private double bonus; 46 47 Manager(String name, String id, double wages, double bonus) { 48 super(name, id, wages); 49 this.setBonus(bonus); 50 } 51 52 public double getBonus() { 53 return bonus; 54 } 55 56 public void setBonus(double bonus) { 57 this.bonus = bonus; 58 } 59 60 } 61 public static void main(String []args){ 62 Test03 setandget = new Test03(); 63 Employee e = setandget.new Employee("bushijie", "HM003", 10000); 64 System.out.println("----------员工类查询-----------"); 65 System.out.println("员工姓名:"+e.getName()+"\r员工编号:"+e.getId()+"\r员工工资:"+e.getWages()+"元整"); 66 System.out.println("----------经理类查询-----------"); 67 Manager m = setandget.new Manager("bushijie", "HM003", 10000,3000); 68 System.out.println("员工姓名:"+m.getName()+"\r员工编号:"+m.getId()+"\r员工工资:"+m.getWages()+"元整" 69 +"\r获得奖金:"+m.getBonus()+"元整"); 70 } 71 } 72 /*运行结果: 73 ----------员工类查询----------- 74 员工姓名:bushijie 75 员工编号:HM003 76 员工工资:10000.0元整 77 ----------经理类查询----------- 78 员工姓名:bushijie 79 员工编号:HM003 80 员工工资:10000.0元整 81 获得奖金:3000.0元整 82 */
1 package com.itheima; 2 3 import java.io.Serializable; 4 import java.lang.reflect.InvocationHandler; 5 import java.lang.reflect.Method; 6 import java.lang.reflect.Proxy; 7 import java.util.ArrayList; 8 import java.util.Collection; 9 import java.util.List; 10 import java.util.RandomAccess; 11 import java.util.concurrent.TimeUnit; 12 13 /*4、 写一个ArrayList类的代理,实现和ArrayList中完全相同的功能,并可以计算每个方法运行的时间。*/ 14 public class Test04 { 15 @SuppressWarnings("unchecked") 16 public static void main(String[] args) { 17 // 定义代理类的类加载器,用于创建代理对象,不一定必须是ArrayList,也可以是其他的类加载器 18 @SuppressWarnings("rawtypes") 19 List <Integer>arrayListProxy = (List<Integer>) Proxy.newProxyInstance( 20 ArrayList.class.getClassLoader(), new Class[] { 21 Serializable.class, Cloneable.class, Iterable.class, 22 Collection.class, List.class, RandomAccess.class }, 23 new InvocationHandler() {// 指派方法调用的调用处理程序,这里用了匿名内部类 24 25 private ArrayList<Integer> target = new ArrayList<Integer>(); //目标对象(真正操作的对象) 26 27 @Override 28 public Object invoke(Object proxy, Method method, 29 Object[] args) throws Throwable { 30 long beginTime = System.currentTimeMillis();//开始时间 31 TimeUnit.SECONDS.sleep(1); 32 Object obj = method.invoke(target, args); //实际调用的方法,并接受方法的返回值 33 long endTime = System.currentTimeMillis();//结束时间 34 System.out.println("方法:-》" + method.getName() 35 + "《-运行的时间为:" + (endTime - beginTime)+"毫秒"); 36 return obj; 37 } 38 }); 39 arrayListProxy.add(90); 40 arrayListProxy.add(168); 41 System.out.println("----看看迭代用时 多少-----"); 42 for(int i : arrayListProxy){ 43 System.out.print(i + "\t"); 44 } 45 } 46 } 47 /*运行结果: 48 方法:-》add《-运行的时间为:1001毫秒 49 方法:-》add《-运行的时间为:1000毫秒 50 ----看看迭代用时 多少----- 51 方法:-》iterator《-运行的时间为:1000毫秒 52 90 168 */
1 package com.itheima; 2 3 /*、 4 编写三各类Ticket、SealWindow、TicketSealCenter分别代表票信息、 5 售票窗口、售票中心。售票中心分配一定数量的票,由若干个售票窗口进行出售, 6 利用你所学的线程知识来模拟此售票过程。*/ 7 public class Test05 { 8 public static void main(String[] args) { 9 Test05 t = new Test05(); 10 t.new Ticket(); 11 } 12 /** 13 * 票信息类 定义了票的总数,和售票窗口数,让售票窗口启动 14 */ 15 class Ticket { 16 public Ticket() { 17 TicketSealCenter tsc = new TicketSealCenter(100);//定义有100张票 18 for (int i = 0; i < 5; i++) {//定义有5个窗口 19 new Thread(new SealWindow(i, tsc)).start();//启动售票窗口售票 20 } 21 } 22 } 23 24 /** 25 * 售票中心类 定义了票的总数,同步售票方法 26 */ 27 class TicketSealCenter { 28 int ticketNum = 50; 29 boolean flag = false; // 定义票是否卖完 30 31 public TicketSealCenter(int num) {//定义一个改变票数的方法 32 this.ticketNum = num; 33 } 34 35 public synchronized void sellTicket(SealWindow s) { 36 if (ticketNum > 0) { 37 int n = s.num+1; 38 System.out.println("第--" + n+ "--售票窗口卖出了第" + ticketNum 39 + "张票!"); 40 ticketNum--; 41 } else { 42 flag = true; 43 } 44 } 45 } 46 47 /** 48 * 售票窗口类 49 */ 50 class SealWindow implements Runnable { 51 int num; 52 TicketSealCenter tsc; 53 54 public SealWindow(int num, TicketSealCenter tsc) { 55 this.num = num; 56 this.tsc = tsc; 57 } 58 59 public final void run() { 60 while (!tsc.flag) { 61 tsc.sellTicket(this); // 调用售票中心类的同步票数 62 try { 63 Thread.sleep(100); 64 } catch (InterruptedException e) { 65 e.printStackTrace(); 66 } 67 } 68 } 69 } 70 } 71 /*运行结果: 72 第--1--售票窗口卖出了第100张票! 73 第--3--售票窗口卖出了第99张票! 74 第--5--售票窗口卖出了第98张票! 75 第--4--售票窗口卖出了第97张票! 76 第--2--售票窗口卖出了第96张票! 77 第--3--售票窗口卖出了第95张票! 78 第--5--售票窗口卖出了第94张票! 79 。。。。*/
1 package com.itheima; 2 3 /*6、 编写一个程序,获取10个1至20的随机数,要求随机数不能重复。*/ 4 public class Test06 { 5 public static void main(String[] args) throws InterruptedException { 6 int[] number = new int[10];//定义一个int数组长度为10 7 for (int i = 0; i < 10; i++) { 8 number[i] = (int) (Math.random() * 20 + 1);//返回1~20之间的随机整数给number[i] 9 for (int j = 0; j < i; j++) { 10 if (number[i] == number[j]) {//与之前的数对比,防止重复 11 i--; 12 break; 13 } 14 } 15 } 16 System.out.println("10个1至20的随机数如下:"); 17 for (int n :number) { 18 Thread.sleep(100);//为了打印好看些 19 System.out.print(n + " "); 20 } 21 } 22 } 23 /*10个1至20的随机数如下: 24 13 12 4 18 9 7 10 11 16 20 */
1 package com.itheima; 2 3 import java.io.BufferedReader; 4 import java.io.FileReader; 5 import java.io.IOException; 6 7 /*7、 把当前文件中的所有文本拷贝,存入一个txt文件,统计每个字符出现的次数并输出,例如: 8 9 a: 21 次 10 b: 15 次 11 c:: 15 次 12 把: 7 次 13 当: 9 次 14 前: 3 次 15 ,:30 次*/ 16 public class Test07 { 17 public static void main(String[] args) throws IOException { 18 // 读取文本内容 19 //String str = new String(" 把当前文件中的所有文本拷贝,存入一个txt文件,统计每个字符出现的次数并输出,例如:"); 20 BufferedReader in = new BufferedReader(new FileReader("c:\\exam.txt")); 21 String str = null, s2 = new String(); 22 while ((s2 = in.readLine()) != null) 23 str += s2 + "\n";// 如果s2不为空,将s2中的读到的每一行换行后给str 24 in.close(); 25 int len = 0; 26 while (str.length() > 0) { 27 len = str.length(); // 获取第一个字符 28 String s = str.substring(0, 1); // 用空格替换,以便计算这个字符的个数 29 str = str.replaceAll(s, ""); // 写入文件,加\r\n换行 30 System.out.print(s + ":出现" + (len - str.length()) + "次\r\n"); 31 32 } 33 } 34 } 35 /*运行结果: 36 n:出现18次 37 u:出现11次 38 l:出现28次 39 黑:出现1次 40 马:出现1次 41 程:出现5次*/
1 package com.itheima; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.List; 6 7 /*8、 编写程序,生成5个1至10之间的随机整数,存入一个List集合, 8 编写方法对List集合进行排序(自定义排序算法,禁用Collections.sort方法和TreeSet), 9 然后遍历集合输出。*/ 10 public class Test08 { 11 public static void main(String[] args) throws InterruptedException { 12 int[] number = new int[5];// 定义一个int数组长度为5 13 List<Integer> list = new ArrayList<Integer>();// 定义一个int数组长度为5 14 for (int i = 0; i < 5; i++) { 15 number[i] = (int) (Math.random() * 10 + 1);// 返回1~10之间的随机整数给number[i] 16 for (int j = 0; j < i; j++) { 17 if (number[i] == number[j]) {// 与之前的数对比,防止重复 18 i--; 19 break; 20 } 21 } 22 } 23 System.out.println("将随机数添加到list集合中"); 24 for (int n : number) { 25 Thread.sleep(100);// 为了打印好看些 26 list.add(n); 27 System.out.print(n + " "); 28 } 29 System.out.println("\n5个1至10的随机数从小到大排序如下:"); 30 Collections.sort(list);// 按升序排序 31 // 冒泡排序 32 for (int i = 0; i < list.size() - 1; i++) { 33 for (int j = 1; j < list.size() - i; j++) { 34 if ((list.get(j - 1)).compareTo(list.get(j)) > 0) { // 比较两个整数的大小 35 int temp = list.get(j - 1); // 如果J-1大于J的交换位置 36 list.set((j - 1), list.get(j)); 37 list.set(j, temp); 38 } 39 } 40 } 41 //遍历输出 42 for (int n : list) { 43 Thread.sleep(100);// 为了打印好看些 44 System.out.print(n + " "); 45 } 46 } 47 } 48 /*输出结果: 49 将随机数添加到list集合中 50 1 4 8 9 6 51 5个1至10的随机数从小到大排序如下: 52 1 4 6 8 9 */
1 package com.itheima; 2 3 import java.util.Arrays; 4 5 /*9、 在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符, 6 如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),否则,返回-1。 7 要搜索的字符数组和字符都以参数形式传递传递给该方法,如果传入的数组为null, 8 应抛出IllegalArgumentException异常。在类的main方法中以各种可能出现的情况测试验证该方法编写得是否正确, 9 例如,字符不存在,字符存在,传入的数组为null等。*/ 10 11 public class Test09 { 12 int frequency = 0; 13 public static void main(String[] args) { 14 Test09 t = new Test09(); 15 t.seach(new String[] {"04训练营", "01卜世杰", "05我来了", "03程序员", "02黑马" }); 16 t.seach(new String[]{});//传入空字符 17 } 18 void seach(String arr[]) { 19 frequency++; 20 System.out.println("--第"+frequency+"次----进入查询系统"); 21 if(arr.length==0){ 22 System.out.println("您传入的数组为null,抛出异常"); 23 new IllegalArgumentException().printStackTrace();//抛异常 24 return;//跳出方法 25 } 26 27 System.out.println("排序前的数组:"); 28 for (String a : arr) { 29 System.out.print(a + " "); 30 } 31 Arrays.sort(arr);// 查找前得排序 32 System.out.println("\r排序后的数组:"); 33 for (String a : arr) { 34 System.out.print(a + " "); 35 } 36 System.out.println("\r-----查询结果如下-----"); 37 int index = Arrays.binarySearch(arr,"02黑马");//进行查询 38 if (index == -1) { 39 System.out.println("查询内容不存在!"); 40 } else { 41 System.out.println("查询内容存在,序列号为:" + index); 42 } 43 } 44 } 45 /*运行结果 46 --第1次----进入查询系统 47 排序前的数组: 48 04训练营 01卜世杰 05我来了 03程序员 02黑马 49 排序后的数组: 50 01卜世杰 02黑马 03程序员 04训练营 05我来了 51 -----查询结果如下----- 52 查询内容存在,序列号为:1 53 --第2次----进入查询系统 54 您传入的数组为null,抛出异常 55 java.lang.IllegalArgumentException 56 at com.itheima.Test09.seach(Test09.java:24) 57 at com.itheima.Test09.main(Test09.java:16)*/
1 package com.itheima; 2 3 /*10、 金额转换,阿拉伯数字转换成中国传统形式。 4 * 5 壹仟零佰壹拾零亿零仟零佰零拾零万壹仟零佰壹拾零元整 6 例如:101000001010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整*/ 7 8 public class Test10 { 9 public static String Change(String money){ 10 String[] Monetary = {"元","拾","佰","仟","万", 11 "拾","佰","仟","亿","拾","佰","仟"}; 12 String[] Number = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"}; 13 String MONEY =""; 14 for (int i = money.length(); i>0;i--){ 15 //遍历金额的每一位 16 int a = Integer.parseInt(String.valueOf(money.charAt(money.length()-i))); 17 MONEY += Number[a];//将小写数字变成大写 18 MONEY += Monetary[i-1];//在数字后面加单位 19 20 } //未替换前: 壹仟零佰壹拾零亿零仟零佰零拾零万壹仟零佰壹拾零元整 21 //正确结果: 壹仟零壹拾亿零壹仟零壹拾元整 22 return MONEY.replaceAll("零[拾佰仟]", "零").replaceAll("零亿", "亿").replaceAll("零零零零万", "零").replaceAll("零+零万", "万零") 23 .replaceAll("零+元", "元").replaceAll("零零", "零");//此代码顺序很重要。需细细品味。 24 //使用字符串的replaceAll方法和正则表达式进行替换字符。 25 } 26 public static void main (String []args) { 27 System.out.println("您输入的101000001010转换为大写金额如下:\n"+Test10.Change("101000001010" )+"整"); 28 System.out.println("您输入的786024500转换为大写金额如下:\n"+Test10.Change("786024500" )+"整"); 29 System.out.println("您输入的500001000转换为大写金额如下:\n"+Test10.Change("500001000" )+"整"); 30 System.out.println("您输入的520001000转换为大写金额如下:\n"+Test10.Change("520001000" )+"整"); 31 System.out.println("您输入的502001000转换为大写金额如下:\n"+Test10.Change("502001000" )+"整"); 32 System.out.println("您输入的1002001000转换为大写金额如下:\n"+Test10.Change("1002001000" )+"整"); 33 } 34 /*您输入的101000001010转换为大写金额如下: 35 壹仟零壹拾亿零壹仟零壹拾元整 36 您输入的786024500转换为大写金额如下: 37 柒亿捌仟陆佰零贰万肆仟伍佰元整 38 您输入的500001000转换为大写金额如下: 39 伍亿零壹仟元整 40 您输入的520001000转换为大写金额如下: 41 伍亿贰仟万零壹仟元整 42 您输入的502001000转换为大写金额如下: 43 伍亿零贰佰万零壹仟元整 44 您输入的1002001000转换为大写金额如下: 45 壹拾亿零贰佰万零壹仟元整 46 */ 47 }
1 package com.itheima; 2 3 /* 4 * 1.定义一个二维int数组,编写代码获取最小元素。 5 * */ 6 7 public class Test01 { 8 public static void main(String args[]) { 9 // 定义一个二维数组 10 int arr[][] = { { 1, 2, 8 }, { 7, 9 } }; 11 // 获取最小元素 12 int min = arr[0][0]; 13 for (int i = 0; i < arr.length; i++) { 14 for (int j = 0; j < arr[i].length; j++) { 15 if (arr[i][j] < min) { 16 min = arr[i][j];//遍历数组将比较后较小的值赋给min 17 } 18 } 19 } 20 System.out.println("min = " + min); 21 } 22 }
1 package com.itheima; 2 /* 3 2、 Collection和Collections有什么关系? 4 List和Set有什么异同点? 5 Map有哪些常用类,各有什么特点? 6 7 一,Collection和Collections有什么关系 8 答: Collection是java.util下的接口,它是一个集合接口。 9 它提供了对集合对象进行基本操作的通用接口方法。 10 Collections是 java.util下的专门为集合类定义的工具类, 11 它提供一系列静态方法, 实现对各种集合的查找、排序、乱序,常规数据处理等操作 。 12 13 二, List和Set有什么异同点? 14 答:List Set 都继承 Colltction 15 List有序,可重复,常用实现类有ArrayList,LinkedList, 16 Set无序,元素唯一 常用实现类有HashSet,TreeSet 17 18 三,Map有哪些常用类,各有什么特点? 19 答: Map接口有3个常用实现类,分别是HashMap ,TreeMap,LinkeHashMap. 20 特点分别是HashMap用于快速保存,查找数据。TreeMap支持排序功能。 21 LinkeHashMap能够保存键值对的添加顺序。 22 23 24 */
1 package com.itheima; 2 /* 3 3、 为什么需要配置path,什么时候需要classpath? 4 答:为何配置path: 5 在cmd命令中输入一个指令时,系统会先在当前文件目录下查找命令文件, 6 path的环境变量中依次查找命令文件,以最先找到的为准,因为配置了path, 7 所以在cmd命令下可以直接输入java和javac等jdk的命令 。 8 9 为何配置classpath: 10 jvm在查找class文件时如果没有设置classpath会在当前路径查找, 11 12 当需要指定查找Class的查找路径时可以设置classpth的路径。 13 那么jvm仅在classpath的路径下查找class文件了。 14 15 16 */
1 package com.itheima; 2 /*package com.itheima; 3 4、 以下代码哪个是正确的?为什么? 4 a. byte b = 1 + 1; 5 b. byte b = 1; b = b + 1; 6 c. byte b = 1; b = b += 1; 7 d. byte b = 1; b = ++b; 8 9 答:acd正确,b错误。 10 a正确,定义了一个byte类型b, 11 b错误,b+1表示一个byte类型数据与一个int类型数据相加,结果会默认向上转型 12 为int类型,而int类型不能直接转换为byte类型。要转需要强制转换,同时要注意精度问题。 13 c正确,b+=1是一次运算,运算符在运算时自动完成强制类型转换。 14 而b选项中的运算是二次运算所以编译错误。 15 d正确,++b也是一次运算,同c 16 17 } 18 */
1 package com.itheima; 2 3 class A { 4 void fun1() { 5 System.out.println(fun2()); 6 } 7 int fun2() { 8 return 123; 9 } 10 } 11 public class Test05 extends A { 12 int fun2() { 13 return 456; 14 } 15 16 public static void main(String args[]) { 17 Test05 b = new Test05();//实例化对象 18 b.fun1();//调用方法 19 A a = b;//将b的内存地址赋给了a 20 a.fun1();//实际上是调用了b的方法 21 //A c =new A(); 22 //c.fun1(); 这里运行结果为123 23 } 24 } 25 /*答:运行结果为456和456 26 分析:b.fun1();表示调用实例化的b对象中fin1方法,而fin1是继承于A方法的 27 Test5继承了A中的方法,并复写了fin2方法,return456.所以结果为456 28 A a = b;//将b的内存地址赋给了a 29 a.fun1();//实际上是调用了b的方法*/
1 package com.itheima; 2 /* 3 * 6、 写出以下代码执行结果,分析为什么?(没有分析结果不得分 4 */ 5 public class Test06 { 6 public static void main(String[] args) { 7 8 String s = "abc"; 9 10 s.substring(1);//截取第一个字符,打印结果为bc 11 12 s.replace("bc", "xyz");//替换字符串,打印结果为axyz 13 14 System.out.println(s); 15 16 String value = new String("abc"); 17 18 System.out.println(s == value); 19 //System.out.println(s.equals(value)); 20 } 21 /*答:运行的结果为 abc 和 false 22 代码中对String类型数据s做了截取字符串和替换字符串操作,, 23 但是并没有将操作后的结果赋值给s。所以输出s仍然为原始数据。 24 在s == value的“==”比较中,该比较方法只会比较对象的引用是否相等, 25 用new方法会重新开辟以快地址空间,所以结果为false 26 如果用equals进行比较则会对字符串包含的内容进行比较*/ 27 28 }
1 package com.itheima; 2 /* 3 * 7、 编写一个延迟加载的单例设计模式。 4 * */ 5 public class Test07{ 6 //懒汉式单例模式是延迟加载的单例设计模式 7 8 public static class LazySingleton { 9 10 //静态私有的成员变量 11 private static LazySingleton instance = null; 12 13 // 私有的构造方法 14 private LazySingleton() {} 15 16 // 如果不加synchronized会导致对线程的访问不安全 17 // 双重锁定检查 18 public static LazySingleton getInstance() { 19 if (instance == null) { 20 synchronized (LazySingleton.class) { 21 if (null == instance) { 22 instance = new LazySingleton(); 23 } 24 } 25 26 } 27 return instance; 28 } 29 } 30 31 }
1 package com.itheima; 2 /* 3 * 8、 throw和throws有什么区别? try、catch、finally分别在什么情况下使用? 4 * */ 5 /*答:一。throw用于抛出一个异常类对象,通常用于处理自定义异常类情况, 6 如 throw new MyException() 7 throws则是在方法声明时告诉调用者该方法需要抛出什么类型的异常。 8 而异常的捕获,处理交由调用该方法者去实施,如 int parselnt(String s)throws NumberFormatException。 9 并且throw和throws的用法是完全不同的,throw是在方法体内部抛出异常, 10 并且要与throws或者try。。。catch语句块结合使用。否则程序无法通过编译。 11 而throws是在方法声明时抛出异常。使程序不会产生编译异常,但是要在调用方法时 12 使用try。。。catch捕获异常进行分析处理 13 二。try、catch、finally是进行异常处理的关键字,在程序中的语句需要 14 正常执行但有可能发生异常时,用 try{需要执行的语句} 15 catch(Exception) 16 {对异常进行处理的语句} 17 finally{一定会被处理的语句} 18 此方法可以友好的处理程序的异常,同时也方便了后期的排除和维护。*/
1 package com.itheima; 2 /*9、 有这样三个类,Person、Student、GoodStudent。 3 其中GoodStudent继承于Student,Student继承于Person。 4 如何证明创建GoodStudent时是否调用了Person的构造函数? 5 在GoodStudent中是否能指定调用Student的哪个构造函数? 6 在GoodStudent中是否能指定调用Person的哪个构造函数? 7 8 答:如果创建GoodStudent时打印出来person中定义的语句,即证明了函数的调用 9 在GoodStudent中是可以指定调用Student的哪个构造函数也可以指定调用Person的哪个构造函数。 10 想要指定调用函数中对应函数可以用super(),或者实例化对象的方法C c = new C();*/ 11 12 13 public class Test09 { 14 15 public static void main(String[] args) { 16 GoodStudent g1 = new GoodStudent();//实例化GoodStudent 17 System.out.println("--------The elegant separation line--------"); 18 } 19 } 20 //依次构造Person、Student、GoodStudent类,对于相应的继承关系 21 class Person { 22 //分别构造不同参数个数的构造函数 23 Person() { 24 System.out.println("证明调用了person"); 25 } 26 27 Person(String arg) { 28 System.out.println(arg+"证明从GoodStudent中调用了有一个参数的构造函数"); 29 } 30 31 Person(String arg1, String arg2) { 32 System.out.println(arg1 + arg2+"------this Person!"); 33 } 34 } 35 //Student继承于Person,分别构造不同参数个数的构造函数 36 class Student extends Person { 37 38 Student() { 39 System.out.println("this Student!"); 40 } 41 Student(String arg) { 42 System.out.println("one arg in student"+arg); 43 } 44 Student(String arg1, String arg2){ 45 System.out.println("证明调用了传入两个参数的构造函数"+arg1+arg2); 46 } 47 48 } 49 //GoodStudent继承于Student 50 class GoodStudent extends Student { 51 52 GoodStudent() { 53 //super("from GoodStudent!"); 54 super("first GoodStudent","---second GoodStudent"); 55 System.out.println("this GoodStudent!"); 56 Person p = new Person("form GoodStudent!"); 57 58 } 59 60 }
1 package com.itheima; 2 /*10、 小明的妈妈每天会给他20元零花钱。 3 平日里,小明先花掉一半,再把一半存起来。 4 每到周日,小明拿到钱后会把所有零花钱花掉一半。 5 请编程计算,从周一开始,小明需要多少天才能存够100元?*/ 6 7 //分析:小明每天得到20元花10元。每天即存了10元,每周日的时候手中得到的钱加上20后除以2 8 //答:代码如下----最后小明在第13天存够了100, 9 public class Test10 { 10 public static void main(String[] args) { 11 int day = 1;// 从第一天开始小明开始存钱 12 int money = 0; 13 while (money < 100) { 14 if (day % 7 != 0) { 15 money += 10; 16 } else if (day % 7 == 0) { 17 money = (money + 20) / 2; 18 } 19 System.out.println("小明第" + day + "天存了" + money+"元"); 20 if (money >= 100) {// 当存的钱大于或者等于100时,break后天数不再累加跳出循环 21 break; 22 } 23 day++; 24 } 25 System.out.println("小明需要" + day + "天才能存够100元"); 26 } 27 } 28 /*运行结果如下 29 小明第1天存了10元 30 小明第2天存了20元 31 小明第3天存了30元 32 小明第4天存了40元 33 小明第5天存了50元 34 小明第6天存了60元 35 小明第7天存了40元 36 小明第8天存了50元 37 小明第9天存了60元 38 小明第10天存了70元 39 小明第11天存了80元 40 小明第12天存了90元 41 小明第13天存了100元 42 小明需要13天才能存够100元*/
1 package com.itheima; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 /* 9 題目:编写一个类,在main方法中定义一个Map对象(采用泛型),加入若干个对象,然后遍历并打印出各元素的key和value。 10 分析: 11 1.创建Map对象 12 2.加入若干对象 13 3.遍历Map对象 14 4.打印元素key和value 15 步骤: 16 1.Map<String,Integer> map = new HashMap<String,Integer>(); 17 2.map.put("小明", 21); 18 3.while(it.hasNext()){ 19 Map.Entry<String,Integer> me = it.next(); 20 } 21 4.System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue()); 22 23 */ 24 public class Test2 { 25 public static void main(String[] args) { 26 //创建Map对象 27 Map<String,Integer> map = new HashMap<String,Integer>(); 28 29 //加入若干对象 30 map.put("小明", 21); 31 map.put("小王", 18); 32 map.put("小李", 45); 33 //遍历Map对象 34 Set<Map.Entry<String,Integer>> set = map.entrySet(); 35 36 Iterator<Map.Entry<String,Integer>> it = set.iterator(); 37 38 while(it.hasNext()){ 39 Map.Entry<String,Integer> me = it.next(); 40 41 //打印元素key和value 42 System.out.println("key:"+me.getKey()+"------"+"value:"+me.getValue()); 43 } 44 } 45 }
1 package com.itheima; 2 3 import java.lang.reflect.Method; 4 5 /* 6 题目:方法中的内部类能不能访问方法中的局部变量,为什么? 7 答:方法中的内部类访问局部变量的时候,局部变量需要被 final 关键字修饰。 8 因为方法中的代码是由上而下顺序执行的,方法运行结束后,局部变量就被销毁, 9 内部类的生命周期可能会比局部变量的生命周期长;看下面的代码,方法中的内部 10 类 Inner.class 调用方法中的局部变量 x ,正常调用的时候内部类能够调用到方 11 法中的局部变量,并将内部类对象 inner 返回,正常调用结束后,如果方法中的局 12 部变量 x 没有被 final 关键字修饰,x 则会被销毁,我们再通过反射的方式去调用 x 13 的时候则会发现找不到变量 x ,如果局部变量 x 被 final 关键字修饰后,则 x 在方 14 法运行结束后不会被销毁,而是常驻在内存中直到 JVM 退出,这样再通过反射调用的 15 时候依然可以找到 x 。 16 */ 17 public class Test3 { 18 public static void main(String[] args) throws Exception { 19 Outer outer = new Outer(); // 正常调用 20 Object object = outer.outerfun(); 21 22 Class clazz = object.getClass(); // 反射调用 23 Method method = clazz.getMethod("innerfun"); 24 method.invoke(object); 25 } 26 } 27 28 class Outer { 29 public Object outerfun() { 30 final int x = 5; 31 class Inner { //内部类Inner 32 public void innerfun() { 33 System.out.println(x); 34 } 35 } 36 Inner inner = new Inner(); 37 inner.innerfun(); 38 return inner; 39 } 40 41 }
posted on 2014-01-23 20:19 GoBackHome 阅读(1202) 评论(0) 收藏 举报