java练习,仅供参考!

欢迎同学们交流讨论。

JDK 1.8 API帮助文档

JDK 1.6 API中文文档

第一次小组作业:模拟双色球彩票

第一次小组作业(一) 控制台版

游戏规则:

• 双色球为红球和蓝球;

• 用户从1-33中自选6个数字(不能重复)代表红球;从1-16中自选1个数字代表蓝球;

• 上图为中奖规则,如一等奖为中6个红球及蓝球,二等奖为仅中6个红球……

• 请自拟六个奖项对应的奖品。

  1. package GroupFirst; 


  2. import java.util.Scanner; 


  3. /** 

  4. * 第一次小组作业:模拟双色球彩票  

  5. * •游戏规则 

  6. * •双色球为红球和蓝球 

  7. * •用户从1-33中自选6个数字(不重复)代表红球;从1-16中自选1个数字代表蓝球 

  8. * •上图为中奖规则,如一等奖为中6个红球及蓝球,二等奖为仅中6个红球…… 

  9. * •请自拟六个奖项对应的奖品 

  10. */ 

  11. public class Balllottery 

  12. { 

  13. private int[] betRedBall = new int[6];//存放选择的6个红球 

  14. private int betBlueBall; //存放选择的1个蓝球 

  15. private Scanner scan = null; //扫描器对象 

  16. private int[] winningRedBall = {1,2,3,4,5,6};//红球中奖号码 

  17. private int winningBlueBall = 7; //蓝球中奖号码 


  18. public static void main(String[] args) 

  19. { 

  20. Balllottery lottery = new Balllottery(); 


  21. //从1-33中自选6个数字(不重复)代表红球 

  22. lottery.seletRedBall();//lottery.seletRedBall(); 

  23. System.out.println("--------红球选择完成-----------"); 


  24. //从1-16中自选1个数字代表蓝球 

  25. lottery.seletBlueBall(); 

  26. System.out.println("--------蓝球选择完成-----------"); 


  27. //投注并开奖; 

  28. int level = lottery.lotteryBetting(); 


  29. //显示奖品;  

  30. lottery.showResults(level); 


  31. } 


  32. public void showResults(int level) 

  33. { 

  34. System.out.println("---------------------------"); 

  35. System.out.print("您的投注为:"); 

  36. for (int i = 0; i < betRedBall.length; i++) 

  37. System.out.printf("%-3d",betRedBall[i]); 

  38. System.out.print(", " + betBlueBall + "\n"); 


  39. System.out.print("开奖号码为:"); 

  40. for (int i = 0; i < winningRedBall.length; i++) 

  41. System.out.printf("%-3d",winningRedBall[i]); 

  42. System.out.print(", " + winningBlueBall + "\n\n"); 


  43. //根据中奖等级分配奖品 

  44. switch (level) 

  45. { 

  46. case 0: System.out.println("抱歉,您没中奖!"); break; 

  47. case 1: System.out.println("一等奖,恭喜您获得自行车一辆!"); break; 

  48. case 2: System.out.println("二等奖,恭喜您获得保温杯一个!"); break; 

  49. case 3: System.out.println("三等奖,恭喜您获得新书包一个!"); break; 

  50. case 4: System.out.println("四等奖,恭喜您获得记事本一个!"); break; 

  51. case 5: System.out.println("五等奖,恭喜您获得签字笔一个!"); break; 

  52. case 6: System.out.println("六等奖,恭喜您获得黑铅笔一个!"); break; 

  53. } 

  54. System.out.println("\n---------------------------"); 

  55. } 


  56. // 从1-33中自选6个数字(不重复)代表红球 

  57. public void seletRedBall() 

  58. { 

  59. //用一个数组来存放33个红球并赋值1-33号 

  60. int[] redBall = new int[33];  

  61. for (int i = 0; i < redBall.length; i++) 

  62. redBall[i] = i + 1; // 1--33 


  63. // used表示已经出现过的红球 ; boolean数组默认初始为false 

  64. boolean[] used = new boolean[redBall.length]; 


  65. int count = 0; //统计下注红球个数 


  66. // 输入6个不重复的红球号码,并存放到bet数组 

  67. //Scanner scan = null; 

  68. scan = new Scanner(System.in); 

  69. System.out.println("请输入6个红球号码(1-33):"); 


  70. while (scan.hasNext()) 

  71. { 

  72. int num = scan.nextInt(); // 获得输入 


  73. // 如果这个号码是1-33号,那么就重新选择 

  74. if (num < 1 || num > 33) 

  75. { 

  76. System.out.println("没有" 

  77. + num + "号,请选1-33号。您还需要选择" 

  78. + (6-count) +"个红球!"); 

  79. continue; 

  80. } 

  81. // 如果这个号码没有被选过,那么就放到bet数组 

  82. if (!used[num]) 

  83. { 

  84. betRedBall[count++] = num; 

  85. used[num] = true; 

  86. System.out.println("已选" 

  87. + num + "号!您还需要选择" 

  88. + (6-count) +"个红球!"); 

  89. } 

  90. else  

  91. { 

  92. System.out.println(num + "号已选过,您还需要选择" 

  93. + (6-count) +"个红球!"); 

  94. } 

  95. // 选完6个红球则跳出循环 

  96. if (count==6) break; 

  97. } 

  98. } 


  99. // 从1-16中自选1个数字代表蓝球  

  100. public void seletBlueBall() 

  101. { 

  102. // 输入1个蓝球号码 

  103. //Scanner scan = null; 

  104. scan = new Scanner(System.in); 

  105. System.out.print("请输入1个蓝球号码(1-16):"); 


  106. while (scan.hasNextLine()) 

  107. { 

  108. int num = scan.nextInt(); // 获得输入 

  109. // 

  110. // 如果这个号码是1-16号,那么就重新选择 

  111. if (num < 1 || num > 16) 

  112. { 

  113. System.out.println("没有" + num + "号,请选1-16号!"); 

  114. continue; 

  115. } 

  116. else 

  117. { 

  118. betBlueBall = num; 

  119. System.out.println("已选" + num + "号!"); 

  120. break; 

  121. } 

  122. } 

  123. } 


  124. // 投注并开奖 

  125. public int lotteryBetting() 

  126. { 

  127. int correctRedCount = 0; // 猜中的红球个数 

  128. boolean correctBlueCount = false; // 是否猜中篮球 


  129. //遍历选择的红球;对比开奖结果 算出中奖的红球个数 

  130. for (int i = 0; i < betRedBall.length; i++) 

  131. { 

  132. for (int j = 0; j < winningRedBall.length; j++) 

  133. { 

  134. if (betRedBall[i] == winningRedBall[j]) 

  135. { 

  136. correctRedCount++; 

  137. continue; 

  138. } 

  139. } 

  140. } 


  141. // 判断是否猜中蓝球 

  142. if (betBlueBall == winningBlueBall) correctBlueCount = true;  


  143. /** 没中奖 返回 0 

  144. * 一等奖 中 6+1 

  145. * 二等奖 中 6+0 

  146. * 三等奖 中 5+1 

  147. * 四等奖 中 5+0 中 4+1 

  148. * 五等奖 中 4+0 中 3+1 

  149. * 六等奖 中 2+1 中 0+1 中 1+1 

  150. */ 

  151. System.out.println("Debug:" 

  152. + correctRedCount + "," + correctBlueCount); 

  153. if (correctRedCount == 6) 

  154. { 

  155. if (correctBlueCount) return 1; 

  156. else return 2; 

  157. } 

  158. if (correctRedCount == 5) 

  159. { 

  160. if (correctBlueCount) return 3; 

  161. else return 4; 

  162. } 

  163. if (correctRedCount == 4) 

  164. { 

  165. if (correctBlueCount) return 4; 

  166. else return 5; 

  167. } 

  168. if (correctBlueCount) 

  169. { 

  170. if (correctRedCount == 3) return 5; 

  171. //else if (correctRedCount == 2) return 6; 

  172. //else if (correctRedCount == 1) return 6; 

  173. else return 6; 


  174. } 

  175. return 0; 

  176. } 

  177. } 

运行结果:

第一次小组作业(二) 界面版

-------------------------2016-11-23 更新

整体概况:

  • JPanel面板的的建立与更新

    窗口所有的组件都是绘制在JPanel上的,主要的变化来自于球的变化;(鼠标单击事件)获取的坐标定位到具体的球,才方便操作球的变化;每一次的变化都要更新面板内容。

  • 开奖号码的绑定与设置

    开奖号码显示在一个JLabel标签中,这样JFrame窗体直接通过JLabel就获取开奖号码;开奖号码按钮可以设置开奖号码,而不(方便)用通过ControlBall控制球类获取。

  • 单击球的变化与清空选择

    我是定义了(红蓝灰)3种类型的球,根据她们的状态来响应不同的颜色或号码;清空选择按钮是分别执行了模拟单个点击已选球的操作。

  • 优化与改进

    (1) 所有的绘制在JPanel上, 故绘制的坐标也是基于JPanel;而JPanel面板又被添加到JFrame窗体上,又因鼠标坐标却是基于JFrame窗体的;这两套坐标不一致,但却要用鼠标的坐标去定位球的坐标,球的坐标相对固定,而JPanel的零点相对JFrame窗体的零点却可能不一致,比如窗体边框发生变化时;两套坐标的对应是个问题,我这里只是用到当前状态的相对差距(9,30),如果窗体发生变化,可能就会不能对应坐标,这样也就会产生 选球“失灵”的情况。

    (2) 设置开奖号码我这里只做了范围判断,并没有做重复判断,算是个小Bug。

    (3) 这里用的的是鼠标响应时间,加上代码可能效率不高,这样不可避免的有延时;其实这里的所有的球可以换作按钮,这样通过组件操作必然方便准确,这样只需重点考虑按钮美观的问题。

运行演示: 我这里已经打包可直接运行(需要jdk环境), 点击下载 .Jar 。

目录结构: 共享的源码只有5个类,有兴趣调试的可以参考此目录。

源码共享: 代码比较长,不在这里贴码了,有兴趣的同学可以点击下载 .rar。

week7 Cylinder(二)

2个文件 cylinder_1.dat, cylinder_0.dat都放在项目根目录的resource包下,内容如下:

7.1 Cylider.java

  1. package week7; 


  2. import java.text.DecimalFormat; 


  3. /** 

  4. * 7.1 创建 Cylinder类,以存储标签、半度; 

  5. * 方法包括获得及设置这些成员变量,计算直径、周长面积及体积。  

  6. */ 

  7. public class Cylinder 

  8. { 

  9. private String lable; //存储标签 

  10. private double radius; //圆柱半径 

  11. private double height; //圆柱的高 

  12. public Cylinder(String lable, double radius, double height) 

  13. { 

  14. this.lable = lable; 

  15. this.radius = radius; 

  16. this.height = height; 

  17. } 


  18. public String getLable() 

  19. { 

  20. return lable; 

  21. } 


  22. public boolean setLable(String lable) 

  23. { 

  24. boolean flag = true; 


  25. if (lable.isEmpty()) flag = false; 

  26. else this.lable = lable.trim(); 

  27. //String.trim()截去字符串开头和末尾的空白 

  28. return flag; 

  29. } 


  30. public double getRadius() 

  31. { 

  32. return radius; 

  33. } 


  34. public void setRadius(double radius) 

  35. { 

  36. this.radius = radius; 

  37. } 


  38. public double getHeight() 

  39. { 

  40. return height; 

  41. } 


  42. public void setHeight(double height) 

  43. { 

  44. this.height = height; 

  45. } 


  46. //返回圆柱底面直径 

  47. public double diameter() 

  48. { 

  49. return radius * 2; 

  50. } 


  51. //返回圆柱底面周长 

  52. public double circumference() 

  53. { 

  54. return diameter() * Math.PI; 

  55. } 


  56. //返回 表面积 = 圆柱底面积×2 + 底面周长×高 

  57. public double area() 

  58. { 

  59. return Math.PI * radius * radius * 2 

  60. + circumference() * height; 

  61. } 


  62. //返回 圆柱底体积 

  63. public double volumn() 

  64. { 

  65. return Math.PI * radius * radius * height; 

  66. } 


  67. @Override 

  68. public String toString() 

  69. { 

  70. String output = null; 

  71. DecimalFormat df = new DecimalFormat("#,##0.0##"); 

  72. output = lable 

  73. + " is a cylinder with radius = " + df.format(radius) 

  74. + " units and height = " + df.format(height) 

  75. + " units, " 

  76. + "\nwhich has diameter = " + df.format(diameter()) 

  77. + " units, circumference = " + df.format(circumference()) 

  78. + " units, " 

  79. + "\narea = " + df.format(area()) 

  80. + " square units, and volume = " + df.format(volumn()) 

  81. + " cubic units.\n"; 

  82. return output; 

  83. } 


  84. public static void main(String[] args) 

  85. { 

  86. Cylinder c1 = new Cylinder("Small Example", 4.0, 10.0); 

  87. Cylinder c2 = new Cylinder("Medium Example", 22.1, 30.6); 

  88. Cylinder c3 = new Cylinder("Large Example", 100.0, 200.0); 

  89. c1.setLable(""); 

  90. System.out.println(c1); 

  91. System.out.println(c2); 

  92. System.out.println(c3); 

  93. } 

  94. } 


7.2 CylinderList.java

  1. package week7; 


  2. import java.text.DecimalFormat; 

  3. import java.util.ArrayList; 


  4. /** 

  5. * 7.2 CylinderList类  

  6. */ 

  7. public class CylinderList 

  8. { 

  9. private String listName; 

  10. private ArrayList<Cylinder> cList; 


  11. CylinderList(String listName, ArrayList<Cylinder> cList) 

  12. { 

  13. this.listName = listName; 

  14. this.cList = cList; 

  15. } 


  16. //返回一个代表几何名字的字符串 

  17. public String getName() 

  18. { 

  19. return listName; 

  20. } 


  21. //返回代表集合中Cylinder对象的个数 

  22. public int numberOfCylinders() 

  23. { 

  24. return cList.size(); 

  25. } 


  26. //返回 所有的Cylinder对象的 高 的和 

  27. public double totalHeight() 

  28. { 

  29. double totalHeight = 0; 

  30. for (Cylinder cylinder : cList) 

  31. { 

  32. totalHeight += cylinder.getHeight(); 

  33. } 

  34. return totalHeight; 

  35. } 


  36. //返回 所有的Cylinder对象的 圆柱底面直径 的和 

  37. public double totalDiameter() 

  38. { 

  39. double totalDiameter = 0; 

  40. for (Cylinder cylinder : cList) 

  41. { 

  42. totalDiameter += cylinder.diameter(); 

  43. } 

  44. return totalDiameter; 

  45. } 


  46. //返回 所有的Cylinder对象的 面积 之和 

  47. public double totalArea() 

  48. { 

  49. double totalArea = 0; 

  50. for (Cylinder cylinder : cList) 

  51. { 

  52. totalArea += cylinder.area(); 

  53. } 

  54. return totalArea; 

  55. } 


  56. //返回 所有的Cylinder对象的 体积 之和 

  57. public double totalVolume() 

  58. { 

  59. double totalVolume = 0; 

  60. for (Cylinder cylinder : cList) 

  61. { 

  62. totalVolume += cylinder.volumn(); 

  63. } 

  64. return totalVolume; 

  65. } 


  66. //返回 所有的Cylinder对象 面积 的 平均值 

  67. public double averageArea() 

  68. { 

  69. double averageArea = 0; 

  70. if (cList.size()>0) 

  71. { 

  72. averageArea = totalArea()/cList.size(); 

  73. } 

  74. return averageArea; 

  75. } 


  76. //返回 所有的Cylinder对象 体积 的 平均值 

  77. public double averageVolume() 

  78. { 

  79. double averageVolume = 0; 

  80. if (cList.size()>0) 

  81. { 

  82. averageVolume = totalVolume()/cList.size(); 

  83. } 

  84. return averageVolume; 

  85. } 


  86. //返回 集合的名字及集合中每一个对象的toString方法 

  87. public String toString() 

  88. { 

  89. String output = "\n" + listName + "\n\n"; 

  90. for (Cylinder cylinder : cList) 

  91. { 

  92. output += (cylinder.toString() + "\n");  

  93. } 

  94. return output; 

  95. } 


  96. //返回 集合的名字及Cylinder对象个数, 

  97. //总面积,总体积,平均面积及平均体积 

  98. public String summaryInfo() 

  99. { 

  100. String output = null; 

  101. DecimalFormat df = new DecimalFormat("#,##0.0##"); 

  102. output = "-----" + listName + " Summary-----" 

  103. + "\nNimber of Cylinders: " + numberOfCylinders() 

  104. + "\nTotal Area: " + df.format(totalArea()) 

  105. + "\nTotal Volume: " + df.format(totalVolume()) 

  106. + "\nTotal Height: " + df.format(totalHeight()) 

  107. + "\nTotal Diameter: " + df.format(totalDiameter()) 

  108. + "\nAverage Area: " + df.format(averageArea()) 

  109. + "\nAverage Volume: " + df.format(averageVolume()); 

  110. return output; 

  111. } 

  112. } 

7.3 CylinderListApp 测试类

  1. package week7; 


  2. import java.io.File; 

  3. import java.io.FileNotFoundException; 

  4. import java.util.ArrayList; 

  5. import java.util.Scanner; 


  6. /** 

  7. * 7.3 CylinderListApp 测试类 

  8. * (a) 打开用户输入的文件并读取第一行作为集合的名字;之后读取其他行, 

  9. * 依次生成Cylinder对象,最后生成CylinderList对象。 

  10. * (b) 输出CylinderList对象(调用toString方法),之后空一行, 

  11. * (c) 输出CylinderList对象的汇总信息(调用summaryInfo方法) 

  12. * 注意: 

  13. * 1)如果输入文件名后出现错误称找不到文件,此时可输出绝对路径 

  14. * 2)读取文件第一行作为集合名称后,使用以scanFile.hasNext() 

  15. * 为条件的while循环反复读入三行,然后创建Cylinder对象 

  16. * 3)输出结果必须与下面测试输出的结果完全一致 

  17. */ 

  18. public class CyliderListApp 

  19. { 

  20. public static void main(String[] args) throws FileNotFoundException 

  21. { 

  22. String lable; 

  23. double radius; 

  24. double height; 

  25. Scanner scan0 = new Scanner(System.in); 

  26. Scanner scan1 = null; 

  27. Scanner inputStream = null; 


  28. ArrayList<Cylinder> cList = new ArrayList<>(10); 

  29. CylinderList cylinderList = null;//new CylinderList(listName, cList) 


  30. System.out.print("Enter file name: "); 

  31. String fileName = scan0.nextLine(); // cylinder_0.dat 

  32. scan0.close(); 


  33. File file = new File("resource/" + fileName); 

  34. if(file.exists()) 

  35. { 

  36. inputStream = new Scanner(file); 


  37. String listName = inputStream.nextLine(); 

  38. while (inputStream.hasNextLine()) 

  39. { 

  40. String line = inputStream.nextLine(); 

  41. //使用逗号分隔line,例:Small Example, 4.0, 10.0 

  42. scan1 = new Scanner(line); 

  43. scan1.useDelimiter(","); 

  44. if (scan1.hasNext()) 

  45. { 

  46. lable = scan1.next(); 

  47. radius = Double.parseDouble(scan1.next()); 

  48. height = Double.parseDouble(scan1.next()); 

  49. //创建Cylinder对象并加入ArrayList<Cylinder>中 

  50. cList.add(new Cylinder(lable, radius, height)); 

  51. } 

  52. scan1.close(); //就近原则,以免出现空指针 

  53. } 

  54. inputStream.close(); 

  55. //初始化CylinderList对象 

  56. cylinderList = new CylinderList(listName, cList); 

  57. System.out.print(cylinderList.toString()); 

  58. System.out.println(cylinderList.summaryInfo()); 

  59. } 

  60. else 

  61. { 

  62. System.out.println(file.getAbsolutePath()); 

  63. } 

  64. } 

  65. } 


运行结果:

week8 Cylinder(三)

-------------------------2016-11-27更新

8.1 Cylider.java

导入使用的是7.1的Cylinder 类

8.2 CylinderList.java

参照 7.2 ;我这里贴出增加的部分;

  1. package week8; 


  2. import java.io.File; 

  3. import java.io.FileNotFoundException; 

  4. import java.text.DecimalFormat; 

  5. import java.util.ArrayList; 

  6. import java.util.Scanner; 


  7. import week7.Cylinder; 


  8. /** 

  9. * 8.2 同7.2 CylinderList类,只是增加了4个方法 

  10. */ 

  11. public class CylinderList 

  12. { 

  13. private String listName = null; 

  14. private Scanner scan = null; 

  15. private Scanner inputStream = null;  

  16. private ArrayList<Cylinder> cList = null; 


  17. /** 

  18. *  

  19. * @param listName 

  20. * @param cList 

  21. */ 

  22. CylinderList(String listName, ArrayList<Cylinder> cList) 

  23. { 

  24. this.listName = listName; 

  25. this.cList = cList; 

  26. } 

  27. /***************************以下为新增方法***********************************/ 

  28. /** 

  29. * 接收一个代表文件名字的字符串参数,读入文件内容将其存储到集合名字变量及 ArrayList类型的集合变量中; 

  30. * 利用集合名字及集合变量生成 CylinderList对象;最后返回该 CylinderList对象; 

  31. * @param fileName 

  32. * @return 

  33. * @throws FileNotFoundException 

  34. */ 

  35. public CylinderList readFile(String fileName) throws FileNotFoundException 

  36. { 

  37. CylinderList cylinderList = null; 

  38. String lable;  

  39. double radius;  

  40. double height; 

  41. String nameList = null; 


  42. //读文件并赋值 

  43. File file = new File(fileName);  

  44. if(file.exists())  

  45. {  

  46. inputStream = new Scanner(file);  


  47. nameList = inputStream.nextLine();  

  48. while (inputStream.hasNextLine())  

  49. {  

  50. String line = inputStream.nextLine();  

  51. //使用逗号分隔line,例:Small Example, 4.0, 10.0  

  52. scan = new Scanner(line);  

  53. scan.useDelimiter(",");  

  54. if (scan.hasNext())  

  55. {  

  56. lable = scan.next();  

  57. radius = Double.parseDouble(scan.next());  

  58. height = Double.parseDouble(scan.next());  

  59. //创建Cylinder对象并加入ArrayList<Cylinder>中  

  60. cList.add(new Cylinder(lable, radius, height));  

  61. } 

  62. } 

  63. cylinderList = new CylinderList(nameList, cList); 

  64. }  

  65. else  

  66. {  

  67. System.out.println(file.getAbsolutePath());  

  68. System.out.println(fileName + " not exists!"); 

  69. } 


  70. return cylinderList; 

  71. } 


  72. /** 

  73. * 添加一个Cylinder对象到CylinderList对象中 

  74. * @param label 

  75. * @param radius 

  76. * @param height 

  77. */ 

  78. public void addCylinder(String label, double radius, double height) 

  79. { 

  80. cList.add(new Cylinder(label, radius, height)); 

  81. } 


  82. /** 

  83. * 接收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象,则返回该对象并删除之; 

  84. * 否则返回 null; 

  85. * @param label 

  86. * @return 

  87. */ 

  88. public Cylinder deleteCylinder(String label) 

  89. { 

  90. Cylinder cylinder = null; 

  91. for (int i = 0; i < cList.size(); i++) 

  92. { 

  93. //如果找到 先赋值 后 删除 

  94. if (cList.get(i).getLable().equalsIgnoreCase(label) == true) 

  95. { 

  96. cylinder = cList.get(i); 

  97. cList.remove(i); 

  98. } 

  99. } 

  100. return cylinder; 

  101. } 


  102. /** 

  103. * 参数接收收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象, 

  104. * 则返回该对象;否则返回 null; 

  105. * @param label 

  106. * @return 

  107. */ 

  108. public Cylinder findCylinder(String label) 

  109. { 

  110. Cylinder cylinder = null; 

  111. for (int i = 0; i < cList.size(); i++) 

  112. { 

  113. //如果找到 赋值 

  114. if (cList.get(i).getLable().equalsIgnoreCase(label) == true) 

  115. { 

  116. cylinder = cList.get(i); 

  117. } 

  118. } 

  119. return cylinder; 

  120. } 

  121. /** 

  122. * String类中两个方法的比较: 

  123. * equals:将此字符串与指定的对象比较。当且仅当该参数不为 null, 

  124. * 并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。  

  125. * equalsIgnoreCase:将此 String 与另一个 String 比较,不考虑大小写。如果两个字符串的长度相同, 

  126. * 并且其中的相应字符都相等(忽略大小写),则认为这两个字符串是相等的。  

  127. */ 

  128. /***************************以上为新增方法*********************************/ 


  129. .... 

  130. } 

8.3 CylinderListMenuApp.java

  1. package week8; 


  2. import java.io.IOException; 

  3. import java.util.ArrayList; 

  4. import java.util.Scanner; 


  5. import week7.Cylinder; 


  6. /** 

  7. * 8.3 CylinderListMenuApp 

  8. * 包含 main 方法,呈现有 7 个选项的菜单 

  9. * (1) 读入文件内容并创建 CylinderList对象 

  10. * (2) 打印输出 CylinderList对象 

  11. * (3) 打印输出 CylinderList对象的汇总信息 

  12. * (4) 增加一个 CylinderList对象至 CylinderList对象中 

  13. * (5) 从 CylinderList对象中删除一个 Cylinder对象 

  14. * (6) 在 CylinderList对象中找到一个 Cylinder对象 

  15. * (7) 退出程序 

  16. * 设计: 

  17. * main方法中将先输出带有描述的 7个选项信息。 

  18. * 一旦用户输入了一个选项编号,则对应 的方法将被调用。 

  19. * 之后再次呈现选项信息,提示用户进行选择。 

  20. */ 

  21. public class CylinderListMenuApp 

  22. { 

  23. /** 

  24. * 显示菜单信息 

  25. */ 

  26. private static void showMenu() 

  27. { 

  28. //输出带有描述的 7个选项信息 

  29. System.out.println("Cylinder List System Menu"); 

  30. System.out.println("R - ReadFile and Create Cylinder List"); 

  31. System.out.println("P - Print Cylinder List"); 

  32. System.out.println("S - Print Summary"); 

  33. System.out.println("A - Add Cylinder"); 

  34. System.out.println("D - Delete Cylinder"); 

  35. System.out.println("F - Find Cylinder"); 

  36. System.out.println("Q - Quit"); 

  37. } 


  38. public static void main(String[] args) throws IOException 

  39. { 

  40. //创建一个 Cylinder集合 

  41. ArrayList<Cylinder> clist = new ArrayList<>(); 


  42. String sName = "***no list name assigned***"; 

  43. CylinderList cylinderList = new CylinderList(sName, clist); 



  44. Scanner scan = new Scanner(System.in); 

  45. char key; //输入的key值 


  46. showMenu(); //显示提示菜单 

  47. while (true) 

  48. { 

  49. //提示用户进行选择 

  50. System.out.print("\nEnter Code [R, P, S, A, D, F or Q]: "); 


  51. key = scan.nextLine().charAt(0); 

  52. switch (key) 

  53. { 

  54. case 'r'://resource/cylinder_1.dat 

  55. case 'R'://ReadFile and Create Cylinder List 

  56. System.out.print("\tFile name: "); 

  57. //读文件转化为CylinderList对象后重新赋值 

  58. cylinderList = cylinderList.readFile(scan.nextLine()); 

  59. System.out.println("\tFile read in and Cylinder List created"); 

  60. break; 

  61. case 'p': 

  62. case 'P'://Print Cylinder List 

  63. System.out.println(cylinderList); 

  64. break; 

  65. case 's': 

  66. case 'S'://Print Summary 

  67. System.out.println(cylinderList.summaryInfo()); 

  68. break; 

  69. case 'a': 

  70. case 'A'://Add Cylinder 

  71. System.out.print("\tLabel: "); 

  72. String labelA = scan.nextLine(); 

  73. System.out.print("\tRadius: "); 

  74. double radius = Double.parseDouble(scan.nextLine()); 

  75. System.out.print("\tHeight: "); 

  76. double height =Double.parseDouble(scan.nextLine()); 

  77. cylinderList.addCylinder(labelA, radius, height); 

  78. System.out.println("\t*** Cylinder added ***"); 

  79. break; 

  80. case 'd': 

  81. case 'D'://Delete Cylinder 

  82. System.out.print("\tLabel: "); 

  83. String labelD = scan.nextLine(); 

  84. if(cylinderList.deleteCylinder(labelD) == null) 

  85. System.out.println("\t\"" + labelD + "\" not found"); 

  86. else 

  87. System.out.println("\t\"" + labelD +"\" deleted"); 

  88. break; 

  89. case 'f': 

  90. case 'F'://Find Cylinder 

  91. System.out.print("\tLabel: "); 

  92. String labelF = scan.nextLine(); 

  93. if(cylinderList.findCylinder(labelF) == null) 

  94. System.out.println("\t\"" + labelF + "\" not found"); 

  95. else 

  96. System.out.println(cylinderList.findCylinder(labelF)); 

  97. break; 

  98. case 'q': 

  99. case 'Q'://Quit 

  100. return; 

  101. default: 

  102. System.out.println("\t*** invalid code ***"); 

  103. } 

  104. } 

  105. } 

  106. } 

运行演示:

week10 继承特性的练习: 货物

-------------------------2016-12-04更新

  • 谨记:重载增加了一个额外的方法,而覆盖取代了方法定义

  • 静态方法不能使用隐含(或明确的把this作为其调用对象) 的实例变量(或非静态方法)

10.1 InventoryItem.java

  1. package week10; 


  2. /** 

  3. * 10.1 InventoryItem.java 

  4. * 货物类:所有物品类的基类 

  5. */ 

  6. public class InventoryItem 

  7. { 

  8. protected String name; 

  9. protected double price; 

  10. private static double taxRate = 0; 


  11. public static void main(String[] args) 

  12. { 

  13. InventoryItem.setTaxRate(0.08); 

  14. InventoryItem item1 = new InventoryItem("Birdseed", 7.99); 

  15. InventoryItem item2 = new InventoryItem("Picture", 10.99); 


  16. System.out.println(item1); 

  17. System.out.println(item2); 

  18. } 


  19. /** 

  20. * 初始化 

  21. * @param name 

  22. * @param price 

  23. */ 

  24. public InventoryItem(String name, double price) 

  25. { 

  26. this.name = name; 

  27. this.price = price; 

  28. } 


  29. @Override 

  30. public String toString() 

  31. { 

  32. return name + ": $" + calculateCost(); 

  33. } 


  34. /** 

  35. * 货物含税的价格 

  36. * @return 

  37. */ 

  38. public double calculateCost() 

  39. { 

  40. return this.price * (1 + taxRate); 

  41. } 


  42. public String getName() 

  43. { 

  44. return name; 

  45. } 


  46. /** 

  47. * 设置税率; 

  48. * 静态方法不能使用隐含(或明确的把this作为其调用对象) 的实例变量(或非静态方法) 

  49. * @param taxRateIn 

  50. */ 

  51. public static void setTaxRate(double taxRateIn) 

  52. { 

  53. taxRate = taxRateIn; 

  54. } 

  55. } 

运行结果:

10.2 ElectronicsItem.java

  1. package week10; 


  2. /** 

  3. * 10.2 ElectronicsItem.java 

  4. * 电子货物类:InventoryItem的派生类 

  5. */ 

  6. public class ElectronicsItem extends InventoryItem 

  7. { 

  8. protected double weight; //电子货物重量 

  9. public static final double SHIPPING_COST = 1.5;//每磅的货运费用 


  10. public ElectronicsItem(String name, double price, double weight) 

  11. { 

  12. super(name, price); 

  13. this.weight = weight; 

  14. } 


  15. @Override 

  16. public double calculateCost() 

  17. { 

  18. return super.calculateCost() + weight * SHIPPING_COST; 

  19. } 


  20. public static void main(String[] args) 

  21. { 

  22. InventoryItem.setTaxRate(0.08); 

  23. ElectronicsItem eItem = new ElectronicsItem("Monitor", 100, 10.0); 

  24. System.out.println(eItem); 

  25. } 

  26. } 


运行结果:

10.3 OnlineTextItem.java

  1. package week10; 


  2. /** 

  3. * 10.3 OnlineTextItem.java 

  4. * 在线文本商品类:InventoryItem的派生类 

  5. * 该类代表用户可购买的在线文本商品(如电子书或者电子杂志); 

  6. * 因为它只是概念级的、 代表物品的类,因此可以设置为抽象类; 

  7. */ 

  8. public abstract class OnlineTextItem extends InventoryItem 

  9. { 


  10. public OnlineTextItem(String name, double price) 

  11. { 

  12. super(name, price); 

  13. // TODO Auto-generated constructor stub 

  14. } 


  15. @Override 

  16. public double calculateCost() 

  17. { 

  18. return price; 

  19. } 


  20. } 


10.4 OnlineArticle.java

  1. package week10; 


  2. /** 

  3. * 10.4 OnlineArticle.java 

  4. * 电子类文本物品:OnlineTextItem的派生类 

  5. */ 

  6. public class OnlineArticle extends OnlineTextItem 

  7. { 

  8. private int wordCount; //记录字数 


  9. public OnlineArticle(String name, double price) 

  10. { 

  11. super(name, price); 

  12. this.wordCount = 0; 

  13. } 


  14. @Override 

  15. public String toString() 

  16. { 

  17. return name + ": $"+ price  

  18. + " " + this.wordCount;  

  19. } 


  20. public void setWordCount(int wordCount) 

  21. { 

  22. this.wordCount = wordCount; 

  23. } 


  24. } 


10.5 OnlineBook.java

  1. package week10; 


  2. /** 

  3. * 10.5 OnlineBook.java 

  4. * 电子书:OnlineTextItem的派生类 

  5. */ 

  6. public class OnlineBook extends OnlineTextItem 

  7. { 

  8. protected String author; //电子书作者 


  9. public OnlineBook(String name, double price) 

  10. { 

  11. super(name, price); 

  12. author = "Author Not Listed"; 

  13. } 


  14. public void setAuthor(String author) 

  15. { 

  16. this.author = author; 

  17. } 


  18. @Override 

  19. public String toString() 

  20. { 

  21. return name + " - " 

  22. + author +": $" + price; 

  23. } 


  24. public static void main(String[] args) 

  25. { 

  26. OnlineBook book = new OnlineBook("A Novel Novel", 9.99); 

  27. System.out.println(book); 


  28. book.setAuthor("Jane Lane"); 

  29. System.out.println(book); 

  30. } 


  31. } 


运行结果:

10.6 InventoryApp.java

  1. package week10; 


  2. /** 

  3. * 10.6 InventoryApp.java 

  4. * 测试类: 

  5. * (1) 设置税率为 0.05 

  6. * (2) 初始化并输出 4个对象(item1、item2、item3、item4) 

  7. */ 

  8. public class InventoryApp 

  9. { 

  10. public static void main(String[] args) 

  11. { 

  12. InventoryItem.setTaxRate(0.05); 


  13. InventoryItem item1 = new InventoryItem("pen", 25); 

  14. ElectronicsItem item2 = new ElectronicsItem("apple phone", 1000, 1.8); 

  15. OnlineArticle item3 = new OnlineArticle("Java", 8.5); 

  16. OnlineBook item4 = new OnlineBook("Head first Java", 40); 


  17. item3.setWordCount(700); 

  18. item4.setAuthor("Kathy&Bert"); 


  19. System.out.println(item1); 

  20. System.out.println(item2); 

  21. System.out.println(item3); 

  22. System.out.println(item4); 


  23. System.out.println("All inventory:\n\n" + myItems); 

  24. System.out.println("Total: " + myItems.calculateTotal(2)); 

  25. } 

  26. } 


运行结果:

week11 继承的多态特性:货物列表

-------------------------2016-12-05更新

任务:在week10的基础上完成该实验任务。生成2个新的类,并体会继承的多态特性。

11.7 ItemsList.java

  1. package week11; 


  2. import week10.ElectronicsItem; 

  3. import week10.InventoryItem; 


  4. /** 

  5. * 11.7 ItemsList.java 

  6. * 存放InventoryItem对象的数组 

  7. */ 

  8. public class ItemsList 

  9. { 

  10. private InventoryItem[] inventory; 

  11. private int count; 


  12. public ItemsList() 

  13. { 

  14. inventory = new InventoryItem[20]; 

  15. count = 0; 

  16. } 


  17. /** 

  18. * 增加一个item 

  19. * @param itemIn 

  20. */ 

  21. public void addItem(InventoryItem itemIn) 

  22. { 

  23. this.inventory[count++] = itemIn; 

  24. } 


  25. /** 

  26. * 返回代表数组各元素价格的总和 

  27. * @param electronicsSurcharge,代表征收ElectronicsItem的附加费 

  28. * @return 

  29. */ 

  30. public double calculateTotal(double electronicsSurcharge) 

  31. { 

  32. double totalCost = 0; 


  33. /** 需要遍历 inventory数组的每一个元素,将价格 (cost)累加到和上。 

  34. * 如果元素为 ElectronicsItem类的引用变量 ,则激活calculateCost方法, 

  35. * 增加该的 方法的electronicsSurcharge 

  36. */ 

  37. for (int i = 0; i < count; i++) 

  38. { 

  39. if (inventory[i] instanceof ElectronicsItem) 

  40. { 

  41. totalCost += inventory[i].calculateCost() + electronicsSurcharge; 

  42. } 

  43. else 

  44. { 

  45. totalCost += inventory[i].calculateCost(); 

  46. } 


  47. } 

  48. return totalCost; 

  49. } 


  50. @Override 

  51. public String toString() 

  52. { 

  53. String output = ""; 

  54. for (int i = 0; i < count; i++) 

  55. { 

  56. output += inventory[i].toString(); 

  57. output += "\n"; 

  58. } 

  59. return output; 

  60. } 

  61. } 

11.8 ItemsListApp.java

  1. package week11; 


  2. import week10.ElectronicsItem; 

  3. import week10.InventoryItem; 

  4. import week10.OnlineArticle; 

  5. import week10.OnlineBook; 


  6. /** 

  7. * 11.8 ItemsListApp.java 测试类 

  8. */ 

  9. public class ItemListApp 

  10. { 

  11. public static void main(String[] args) 

  12. { 

  13. // a)初始化名为myItems的ItemsList对象 

  14. ItemsList myItems = new ItemsList(); 


  15. // b)通过InventoryItem的setTaxRate方法设置税率为 0.05 

  16. InventoryItem.setTaxRate(0.05); 


  17. // c)初始化以下4个货物并将其增加到myItems中 

  18. ElectronicsItem electItem = new ElectronicsItem("笔记本", 1234.56, 10); 

  19. InventoryItem item = new InventoryItem("机油", 9.8); 

  20. OnlineBook book = new OnlineBook("疯狂Java讲义", 12.3); 

  21. book.setAuthor("李刚"); 

  22. OnlineArticle article = new OnlineArticle("如何学好Java", 3.4); 

  23. article.setWordCount(700); 


  24. myItems.addItem(electItem); 

  25. myItems.addItem(item); 

  26. myItems.addItem(book); 

  27. myItems.addItem(article); 


  28. System.out.println("All inventory:\n\n" + myItems); 


  29. System.out.println("Total: " + myItems.calculateTotal(1.215)); 

  30. } 


  31. } 

运行结果:

week12 继承与多态:行程(一)

-------------------------2016-12-20更新

小变动:

  • 参考13周的截图(修改)写的 toString 方法

  • 参考13周的截图,我将类Business的静态常量AWARDMILESFACTOR初始化为2

重难点:

  • 泛型接口 Comparable<T> 的使用

  • java.util.Arrays 中排序方法sort的使用

说 明:

题目所给文本(各类机票数据示例.txt)的票据信息我用表格形式展示如下:

12.1 旅程类:Itinerary

  1. package week12; 


  2. /** 

  3. * 12.1 旅程类 

  4. */ 

  5. public class Itinerary 

  6. { 

  7. private String formAirport; 

  8. private String toAirport; 

  9. private String depDateTime; 

  10. private String arrDateTime; 

  11. private int miles; 


  12. public Itinerary 

  13. (String formAirport,String toAirport,String depDateTime,String arrDateTime,int miles) 

  14. { 

  15. this.formAirport = formAirport; 

  16. this.toAirport = toAirport; 

  17. this.depDateTime = depDateTime; 

  18. this.arrDateTime = arrDateTime; 

  19. this.miles = miles; 

  20. } 


  21. public String getDepDateTime() 

  22. { 

  23. return depDateTime; 

  24. } 


  25. public String getArrDateTime() 

  26. { 

  27. return arrDateTime; 

  28. } 


  29. public int getMiles() 

  30. { 

  31. return miles; 

  32. } 


  33. @Override 

  34. public String toString() 

  35. { 

  36. String output = "" 

  37. + "" + formAirport 

  38. + "-" + toAirport 

  39. + " (" + depDateTime 

  40. + " - " + arrDateTime 

  41. + ")" 

  42. + " " + miles; 

  43. return output; 

  44. } 

  45. } 

12.2 飞机票(抽象)基类:AirTicket

  1. package week12; 


  2. import java.text.DecimalFormat; 

  3. import java.text.Format; 


  4. /** 

  5. * 12.2 飞机票(抽象)基类 

  6. */ 

  7. public abstract class AirTicket implements Comparable<AirTicket> 

  8. { 

  9. private String flightNum; //航班号 

  10. private Itinerary itinerary; //行程 

  11. private double baseFare; //飞机票基本费用 

  12. private double fareAdjustmentFactor; //费用调整因素 


  13. public AirTicket(String flightNum,Itinerary itinerary,double baseFare,double fareAdjustmentFactor) 

  14. { 

  15. this.flightNum = flightNum; 

  16. this.itinerary = itinerary; 

  17. this.baseFare = baseFare; 

  18. this.fareAdjustmentFactor = fareAdjustmentFactor; 

  19. } 


  20. public String getFlightNum() 

  21. { 

  22. return flightNum; 

  23. } 


  24. public Itinerary getItinerary() 

  25. { 

  26. return itinerary; 

  27. } 


  28. public double getBaseFare() 

  29. { 

  30. return baseFare; 

  31. } 


  32. public double getFareAdjustmentFactor() 

  33. { 

  34. return fareAdjustmentFactor; 

  35. } 


  36. /** 

  37. * 自然比较方法:(忽略大小写)比较航班号 

  38. * @return 该对象小于、等于或大于指定对象 at,分别返回负整数、零或正整数。  

  39. */ 

  40. @Override 

  41. public int compareTo(AirTicket at) 

  42. { 

  43. return flightNum.compareToIgnoreCase(at.flightNum); 

  44. } 


  45. @Override 

  46. public String toString() 

  47. { 

  48. Format formater = new DecimalFormat("###,###.00"); 

  49. String output = "" 

  50. + "\nFlight: " + flightNum 

  51. + "\n" + itinerary 

  52. + " (" + totalAwardMiles() + " award miles)" 

  53. + "\nBase Fare: $" + formater.format(baseFare) 

  54. + " Fare Adjustment Factor: " + fareAdjustmentFactor 

  55. + "\nTotal Fare: $" + formater.format(totalFare()) 

  56. + "\t"; 

  57. return output; 

  58. } 


  59. public abstract double totalFare(); 


  60. public abstract double totalAwardMiles(); 


  61. } 

12.3 飞机票子类---经济舱机票:Economy

  1. package week12; 


  2. /** 

  3. * 12.3 飞机票子类---经济舱机票 

  4. */ 

  5. public class Economy extends AirTicket 

  6. { 

  7. private final static double AWARDMILESFACTOR = 1.5; 


  8. public Economy(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor) 

  9. { 

  10. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 

  11. } 


  12. @Override 

  13. public double totalFare() 

  14. { 

  15. return super.getBaseFare() * super.getFareAdjustmentFactor(); 

  16. } 


  17. @Override 

  18. public double totalAwardMiles() 

  19. { 

  20. return super.getItinerary().getMiles() * AWARDMILESFACTOR; 

  21. } 


  22. @Override 

  23. public String toString() 

  24. { 

  25. return super.toString() + " (class Economy)\n " 

  26. + "Includes Award Miles Factor: " 

  27. + AWARDMILESFACTOR; 

  28. } 

  29. } 

12.4 飞机票子类---商务舱机票:Business

  1. package week12; 


  2. /** 

  3. * 12.4 飞机票子类---商务舱机票 

  4. */ 

  5. public class Business extends AirTicket 

  6. { 

  7. private final static double AWARDMILESFACTOR = 2; //这里我改为2(题目为1.5) 

  8. private double foodAndBeverages; 

  9. private double entertaiment; 


  10. public Business(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 

  11. double foodAndBeverages, double entertaiment) 

  12. { 

  13. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 

  14. this.foodAndBeverages = foodAndBeverages; 

  15. this.entertaiment = entertaiment; 

  16. } 


  17. @Override 

  18. public double totalFare() 

  19. { 

  20. return super.getBaseFare() * super.getFareAdjustmentFactor() 

  21. + foodAndBeverages + entertaiment; 

  22. } 


  23. @Override 

  24. public double totalAwardMiles() 

  25. { 

  26. return super.getItinerary().getMiles() * AWARDMILESFACTOR; 

  27. } 


  28. @Override 

  29. public String toString() 

  30. { 

  31. return super.toString()+ " (class Business)\n " 

  32. + "Includes Food/Beverage: $" + foodAndBeverages 

  33. + " Entertaiment: $" + entertaiment; 

  34. } 


  35. } 

12.5 飞机票子类---不可退的机票: NonRefundable

  1. package week12; 


  2. /** 

  3. * 12.5 飞机票子类---不可退的机票 

  4. */ 

  5. public class NonRefundable extends AirTicket 

  6. { 

  7. private double discountFactor; 


  8. public NonRefundable(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 

  9. double discountFactor) 

  10. { 

  11. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 

  12. this.discountFactor = discountFactor; 

  13. } 

  14. @Override 

  15. public double totalFare() 

  16. { 

  17. return super.getBaseFare() * super.getFareAdjustmentFactor() 

  18. * discountFactor; 

  19. } 


  20. @Override 

  21. public double totalAwardMiles() 

  22. { 

  23. return super.getItinerary().getMiles(); 

  24. } 


  25. @Override 

  26. public String toString() 

  27. { 

  28. return super.toString()+ " (class NonRefundable)\n " 

  29. + "Includes DiscountFactor: " 

  30. + discountFactor; 

  31. } 

  32. } 

12.6 飞机票子类---商务舱机票子类---精英类机票: Elite

  1. package week12; 


  2. /** 

  3. * 12.6 飞机票子类---商务舱机票子类---精英类机票 

  4. */ 

  5. public class Elite extends Business 

  6. { 

  7. private double cService; 


  8. public Elite(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 

  9. double foodAndBeverages, double entertaiment, double cService) 

  10. { 

  11. super(flightNum, itinerary, baseFare, fareAdjustmentFactor, foodAndBeverages, entertaiment); 

  12. this.cService = cService; 

  13. } 


  14. @Override 

  15. public double totalFare() 

  16. { 

  17. return super.totalFare() + cService; 

  18. } 


  19. @Override 

  20. public double totalAwardMiles() 

  21. { 

  22. return super.totalAwardMiles(); 

  23. } 


  24. @Override 

  25. public String toString() 

  26. { 

  27. return super.toString()+ " \n " 

  28. + "Includes: Comm Services: $" + cService; 

  29. } 

  30. } 

12.7 测试类: AirTicketProcessor

  1. package week12; 


  2. import java.util.Arrays; 


  3. /** 

  4. * 12.7 测试类 

  5. */ 

  6. public class AirTicketProcessor 

  7. { 

  8. public static void main(String[] args) 

  9. { 

  10. AirTicket[] airTickets = new AirTicket[4]; //四张 飞机票 

  11. Itinerary trip; // 临时行程对象 


  12. // 初始化 题目给出的 四张票 

  13. trip = new Itinerary("ATL", "LGA", "2015/05/01 1500", "2015/05/01 1740", 800); 

  14. Economy economy = new Economy("DL 1867", trip, 450, 1); 

  15. trip = new Itinerary("ATL", "LGA", "2015/05/01 1400", "2015/05/01 1640", 800); 

  16. Business business = new Business("DL 1865", trip, 450, 2, 50, 50); 

  17. trip = new Itinerary("ATL", "LGA", "2015/05/01 0900", "2015/05/01 1140", 800); 

  18. Elite elite = new Elite("DL 1863", trip, 450, 2.5, 50, 50, 100); 

  19. trip = new Itinerary("ATL", "LGA", "2015/05/01 0800", "2015/05/01 1040", 800); 

  20. NonRefundable nonRefundable = new NonRefundable("DL 1861", trip, 450, 0.45, 0.9); 


  21. // 将这4个对象添加到 airTickets  

  22. airTickets[0] = (economy); 

  23. airTickets[1] = (business); 

  24. airTickets[2] = (elite); 

  25. airTickets[3] = (nonRefundable); 


  26. //输出报告 

  27. System.out.println("----------Air Ticket Report-----------"); 

  28. for (int i = 0; i < airTickets.length; i++) 

  29. System.out.println(airTickets[i]); 


  30. Arrays.sort(airTickets); // 按航班号排序并输出报告 

  31. System.out.println("\n----------Air Ticket Report (by Flight Number)-----------"); 

  32. for (int i = 0; i < airTickets.length; i++) 

  33. System.out.println(airTickets[i]); 

  34. } 

  35. } 

运行结果:

week13 继承与多态:行程(二)

-------------------------2016-12-20更新

小变动:

  • 读文件并分割参数我并没有使用Scanner类

  • 读文件的异常处理我没有放在 AirTicketApp 测试类中;(按照题意应在readAirTicketFile方法中throws异常,而不是直接try/catch)

重难点:

  • java.lang.Comparable<T> 接口: 强行对实现它的每个类的对象进行整体排序

  • java.util.Comparator<T> 接口: 强行对某个对象collection进行整体排序的比较函数

  • java.util.Arrays 中方法sort,copyOf的使用

说 明:

a. 有6个类我是直接使用week12的,下面是3个新写的类

b. 题目所给CSV文件(air_ticket_data.csv)我放在工程目录的resource下,如下所示:

  1. B,DL 1865,ATL,LGA,2015/05/01 1400,2015/05/01 1640,800,450,2.0,50.0,50.00 

  2. E,DL 1867,ATL,LGA,2015/05/01 1500,2015/05/01 1740,800,450,1.0 

  3. F,DL 1863,ATL,LGA,2015/05/01 0900,2015/05/01 1140,800,450,2.5,50.0,50.00,100.00 

  4. N,DL 1861,ATL,LGA,2015/05/01 0800,2015/05/01 1040,800,450,0.45,0.90 

  5. B,DL 1866,LGA,ATL,2015/05/01 1400,2015/05/01 1640,800,450,2.0,50.0,50.00 

  6. E,DL 1868,LGA,ATL,2015/05/01 1500,2015/05/01 1740,800,450,1.0 

  7. F,DL 1864,LGA,ATL,2015/05/01 0900,2015/05/01 1140,800,450,2.5,50.0,50.00,100.00 

  8. N,DL 1862,LGA,ATL,2015/05/01 0800,2015/05/01 1040,800,450,0.45,0.90 

-------------------------2016-12-23更新

13.8 功能类: AirTicketProcessor

  1. package week13; 


  2. import java.io.BufferedReader; 

  3. import java.io.File; 

  4. import java.io.FileReader; 

  5. import java.io.IOException; 

  6. import java.util.Arrays; 


  7. import week12.AirTicket; 

  8. import week12.Business; 

  9. import week12.Economy; 

  10. import week12.Elite; 

  11. import week12.Itinerary; 

  12. import week12.NonRefundable; 


  13. /** 

  14. * 13.8 该类完成从数据文件中读取数据并声称报告的功能 

  15. */ 

  16. public class AirTicketProcessor 

  17. { 

  18. private AirTicket[] Tickets; 

  19. private String[] invalidRecords; 


  20. public AirTicketProcessor() 

  21. { 

  22. Tickets = new AirTicket[0]; 

  23. invalidRecords = new String[0]; 

  24. } 


  25. /** 

  26. * 以行为单位读取文件,常用于读面向行的格式化文件 (注意:这个读取文件并分割参数的方法没有使用题目给出的方法) 

  27. */ 

  28. public void readAirTicketFile(String fileName) 

  29. { 

  30. // 这里我设置为 工程 目录的 resource 下 

  31. String path = "resource/" + fileName; 

  32. File file = new File(path); 


  33. BufferedReader reader = null; 

  34. try 

  35. { 

  36. reader = new BufferedReader(new FileReader(file)); 

  37. String tempString = null; // 每行的字符串临时变量 

  38. // 一次读入一行,直到读入null为文件结束 

  39. while ((tempString = reader.readLine()) != null) 

  40. { 

  41. try 

  42. { 

  43. String[] lineArr = tempString.split(","); 

  44. // 以 逗号 为分隔符, 并添加 票据信息 

  45. switch (lineArr[0]) 

  46. { 

  47. case "N": 

  48. addAirTicket(new NonRefundable(lineArr[1], 

  49. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 

  50. Integer.parseInt(lineArr[6])), 

  51. Integer.parseInt(lineArr[7]), Double.parseDouble(lineArr[8]), 

  52. Double.parseDouble(lineArr[9]))); 

  53. break; 

  54. case "E": 

  55. addAirTicket(new Economy(lineArr[1], 

  56. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 

  57. Integer.parseInt(lineArr[6])), 

  58. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]))); 

  59. break; 

  60. case "B": 

  61. addAirTicket(new Business(lineArr[1], 

  62. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 

  63. Integer.parseInt(lineArr[6])), 

  64. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 

  65. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]))); 

  66. break; 

  67. case "F": 

  68. addAirTicket(new Elite(lineArr[1], 

  69. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 

  70. Integer.parseInt(lineArr[6])), 

  71. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 

  72. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]), 

  73. Double.parseDouble(lineArr[11]))); 

  74. break; 

  75. default: 

  76. addInvaildRecord(tempString); 

  77. break; 

  78. } 

  79. } catch (Exception e) 

  80. { 

  81. System.out.println("Line string split error!"); 

  82. } 

  83. } 

  84. } catch (IOException e) 

  85. { 

  86. System.out.println("Not find AirTicketFile!"); 

  87. // e.printStackTrace(); 

  88. } finally 

  89. { 

  90. if (reader != null) 

  91. { 

  92. try 

  93. { 

  94. reader.close(); 

  95. } catch (IOException e1) 

  96. { 

  97. } 

  98. } 

  99. } 

  100. } 


  101. /** 

  102. * 将AirTicket类数组的长度增加1,之后将传入的对象放入数组中 

  103. *  

  104. * @param airTicket 

  105. */ 

  106. public void addAirTicket(AirTicket airTicket) 

  107. { 

  108. Tickets = Arrays.copyOf(Tickets, Tickets.length + 1); 

  109. Tickets[Tickets.length - 1] = (airTicket); 

  110. } 


  111. /** 

  112. * 将invalidRecords数组的长度增加1,将传入的字符串放入数组中(每一行以代表机票种类的 字符开头(N, E, B和F是合法的机票种类), 

  113. * 如果开头字母不在此范围中,则此行为不合法记录) 

  114. *  

  115. * @param lineStr 

  116. */ 

  117. public void addInvaildRecord(String lineStr) 

  118. { 

  119. invalidRecords = Arrays.copyOf(invalidRecords, invalidRecords.length + 1); 

  120. invalidRecords[invalidRecords.length - 1] = (lineStr); 

  121. } 


  122. /** 

  123. * 返回 AirTickets报告 

  124. */ 

  125. public String generateReport() 

  126. { 

  127. String output = ""; 

  128. for (AirTicket airTicket : Tickets) 

  129. { 

  130. output += airTicket + "\n"; 

  131. } 

  132. return output; 

  133. } 


  134. /** 

  135. * 以航班号的升序 返回AirTickets报告 

  136. */ 

  137. public String generateReportByFlightNum() 

  138. { 

  139. String output = ""; 


  140. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 

  141. Arrays.sort(orderT); 


  142. for (AirTicket airTicket : orderT) 

  143. { 

  144. output += airTicket + "\n"; 

  145. } 

  146. return output; 

  147. } 


  148. /** 

  149. * 以行程的升序 返回AirTickets报告 

  150. */ 

  151. public String generateReportByItinerary() 

  152. { 

  153. String output = ""; 


  154. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 

  155. Arrays.sort(orderT, new ItineraryCompare()); 


  156. for (AirTicket airTicket : orderT) 

  157. { 

  158. output += airTicket + "\n"; 

  159. } 

  160. return output; 

  161. } 

  162. } 

13.9 自定义排序类: ItineraryCompare

  1. package week13; 


  2. import java.util.Comparator; 


  3. import week12.AirTicket; 


  4. /** 

  5. * 13.9 按照 Itinerary的tostring值由低到高排序 

  6. */ 

  7. public class ItineraryCompare implements Comparator<AirTicket> 

  8. { 

  9. /** 

  10. * @return 根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。 

  11. */ 

  12. @Override 

  13. public int compare(AirTicket t1, AirTicket t2) 

  14. { 

  15. return t1.getItinerary().toString().compareTo(t2.getItinerary().toString()); 

  16. } 

  17. } 

13.10 测试类: AirTicketApp

  1. package week13; 


  2. import java.util.Scanner; 


  3. /** 

  4. * 13.10 测试类 

  5. */ 

  6. public class AirTicketApp 

  7. { 

  8. public static void main(String[] args) 

  9. { 

  10. // 1. 创建AirTicketProcessor对象 

  11. AirTicketProcessor atp = new AirTicketProcessor();  


  12. // 2. 判断命令行是否有参数(args.lengh的长度是否为0), 

  13. // 如果没有,则输出“命令行中没有提供文件名,程序终止” 

  14. Scanner scan = new Scanner(System.in); 


  15. System.out.print("请输入文件名:"); // air_ticket_data.csv 

  16. String fileName = scan.nextLine(); 

  17. scan.close(); 

  18. if (fileName.length() == 0) 

  19. { 

  20. System.out.println("命令行中没有提供文件名,程序终止"); 

  21. System.exit(0); 

  22. } 


  23. // 3.调用 AirTicketProcessor的方法读入数据文件,输出三个报告。 

  24. atp.readAirTicketFile(fileName); 

  25. System.out.println("----------Air Ticket Report-----------"); 

  26. System.out.println(atp.generateReport()); 

  27. System.out.println("----------Air Ticket Report (by Flight Number)-----------"); 

  28. System.out.println(atp.generateReportByFlightNum()); 

  29. System.out.println("----------Air Ticket Report (by Itinerary)-----------"); 

  30. System.out.println(atp.generateReportByItinerary()); 


  31. // 期间有如果没有找到文件,则抛出异常“文件没有找到,程序终止” 

  32. // (我已经在AirTicketProcessor中捕获异常,故这里省略了。) 

  33. // (如果按照题目意思,需要将readAirTicketFile方法中 抛出异常,在这里捕获即可。) 

  34. } 

  35. } 

运行结果:

第二次小组作业:???

java-7311练习(下)的更多相关文章

  1. java从基础知识(十)java多线程(下)

    首先介绍可见性.原子性.有序性.重排序这几个概念 原子性:即一个操作或多个操作要么全部执行并且执行的过程不会被任何因素打断,要么都不执行. 可见性:一个线程对共享变量值的修改,能够及时地被其它线程看到 ...

  2. Java和C#下的参数验证

    参数的输入和验证问题是开发时经常遇到的,一般的验证方法如下: public bool Register(string name, int age) { if (string.IsNullOrEmpty ...

  3. spring java 获取webapp下文件路径

    spring java 获取webapp下文件路径 @RequestMapping("/act/worldcup_schedule_time/imgdownload") @Resp ...

  4. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  5. Java基础(下)(JVM、API)

    Java基础(下) 第三部分:Java源程序的编辑 我们知道,计算机是不能直接理解源代码中的高级语言,只能直接理解机器语言,所以必须要把高级语言翻译成机器语言,计算机才能执行高级语言编写的程序. 翻译 ...

  6. java 提取目录下所有子目录的文件到指定位置

    package folder; import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundExcept ...

  7. java在cmd下编译引用第三方jar包

    java在cmd下编译引用第三方jar包 转 https://blog.csdn.net/qq_21439971/article/details/53924594 获取第三方jar包 第三包我们可以引 ...

  8. 解决:java 读取 resources 下面的 json 文件

    前言:java 读取 工程下的配置文件,文件类型为 json(*.json),记录一下始终读取不到 json 文件的坑.maven项目 直接上工具类代码 package com.yule.compon ...

  9. JVM(四):深入分析Java字节码-下

    JVM(四):深入分析Java字节码-下 在上文中,我们讲解了 Class 文件中的文件标识,常量池等内容.在本文中,我们就详细说一下剩下的指令集内容,阐述其分别代表了什么含义,以及 JVM 团队这样 ...

  10. 《ElasticSearch6.x实战教程》之复杂搜索、Java客户端(下)

    第八章-复杂搜索 黑夜给了我黑色的眼睛,我却用它寻找光明. 经过了解简单的API和简单搜索,已经基本上能应付大部分的使用场景.可是非关系型数据库数据的文档数据往往又多又杂,各种各样冗余的字段,组成了一 ...

随机推荐

  1. eclipse导入PIL报错

    有些模块,比如PIL,已经装入过,但是在pydev中无法自动提示,甚至有报 unresolved import的问题,虽然不会引起运行时问题,但是无法实现自动提示,还是一件很麻烦的事情. 下面有个解决 ...

  2. 循序渐进Python3(十)-- 2 -- SqlAlchemy

    ORM             对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类 ...

  3. jquery radio

    取radio的值: JS代码 $("input[name='radioName'][checked]").val(); 给radio 赋值, 选中值为2的radio: JS代码 $ ...

  4. C# basic

    1. output Console.WriteLine("hello world"); 2. naming convention variable: start with lowe ...

  5. <转> Lua使用心得(2)

    在lua脚本调用中,如果我们碰到一种不好的脚本,例如: do do end 那我们的程序主线程也会被阻塞住.那我们如何防止这种问题呢?下面就给出一个解决的办法. 首先为了不阻塞主线程,那我们就要开一个 ...

  6. js面向对象编程:if中可以使用那些作为判断条件呢?

    作者来源http://www.2cto.com/kf/201407/314978.html搬运 在所有编程语言中if是最长用的判断之一,但在js中到底哪些东西可以在if中式作为判断表达式呢? 例如如何 ...

  7. mysql计划字段中有多少个逗号,或者某个标识符

    eg:计划url中有多少个小数点 select length('www.mysql.com')-length(REPLACE('www.mysql.com','.',''));

  8. mysql学习(1)-linux操作系统源码包安装

    背景: CentOS 6.4下通过yum安装的MySQL是5.1版的,比较老,所以就想通过源代码安装高版本的5.6.22. 正文: 一:卸载旧版本 使用下面的命令检查是否安装有MySQL Server ...

  9. Fatal error in launcher: Unable to create process using '"'

    今天遇到了 Fatal error in launcher: Unable to create process using '"' 这个问题,原来是我上次装python3.5的时候,pyth ...

  10. MySQL命令实例

    显示数据表结构 1.desc(describe) tablename;2.show columns from tablename;3.use information_schema;    select ...