java-7311练习(下)

java练习,仅供参考!
欢迎同学们交流讨论。

JDK 1.8 API帮助文档
JDK 1.6 API中文文档

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

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

 

enter description here

 

游戏规则:
• 双色球为红球和蓝球;
• 用户从1-33中自选6个数字(不能重复)代表红球;从1-16中自选1个数字代表蓝球;
• 上图为中奖规则,如一等奖为中6个红球及蓝球,二等奖为仅中6个红球……
• 请自拟六个奖项对应的奖品。

package GroupFirst; 
 
import java.util.Scanner; 
 
/** 
 * 第一次小组作业:模拟双色球彩票  
 * •游戏规则 
 * •双色球为红球和蓝球 
 * •用户从1-33中自选6个数字(不重复)代表红球;从1-16中自选1个数字代表蓝球 
 * •上图为中奖规则,如一等奖为中6个红球及蓝球,二等奖为仅中6个红球…… 
 * •请自拟六个奖项对应的奖品 
 */ 
public class Balllottery 
{ 
    private int[] betRedBall = new int[6];//存放选择的6个红球 
    private int betBlueBall;             //存放选择的1个蓝球 
    private Scanner scan = null;        //扫描器对象 
    private int[] winningRedBall = {1,2,3,4,5,6};//红球中奖号码 
    private int winningBlueBall = 7;   //蓝球中奖号码 
 
    public static void main(String[] args) 
    { 
        Balllottery lottery = new Balllottery(); 
 
        //从1-33中自选6个数字(不重复)代表红球 
        lottery.seletRedBall();//lottery.seletRedBall(); 
        System.out.println("--------红球选择完成-----------"); 
         
        //从1-16中自选1个数字代表蓝球 
        lottery.seletBlueBall(); 
        System.out.println("--------蓝球选择完成-----------"); 
         
        //投注并开奖; 
        int level = lottery.lotteryBetting(); 
         
        //显示奖品;  
        lottery.showResults(level); 
         
    } 
 
    public void showResults(int level) 
    { 
        System.out.println("---------------------------"); 
        System.out.print("您的投注为:"); 
        for (int i = 0; i < betRedBall.length; i++) 
            System.out.printf("%-3d",betRedBall[i]); 
        System.out.print(", " + betBlueBall + "\n"); 
         
        System.out.print("开奖号码为:"); 
        for (int i = 0; i < winningRedBall.length; i++) 
            System.out.printf("%-3d",winningRedBall[i]); 
        System.out.print(", " + winningBlueBall + "\n\n"); 
         
        //根据中奖等级分配奖品 
        switch (level) 
        { 
        case 0: System.out.println("抱歉,您没中奖!"); break; 
        case 1: System.out.println("一等奖,恭喜您获得自行车一辆!"); break; 
        case 2: System.out.println("二等奖,恭喜您获得保温杯一个!"); break; 
        case 3: System.out.println("三等奖,恭喜您获得新书包一个!"); break; 
        case 4: System.out.println("四等奖,恭喜您获得记事本一个!"); break; 
        case 5: System.out.println("五等奖,恭喜您获得签字笔一个!"); break; 
        case 6: System.out.println("六等奖,恭喜您获得黑铅笔一个!"); break; 
        } 
        System.out.println("\n---------------------------"); 
    } 
 
    // 从1-33中自选6个数字(不重复)代表红球 
    public void seletRedBall() 
    { 
        //用一个数组来存放33个红球并赋值1-33号 
        int[] redBall = new int[33];  
        for (int i = 0; i < redBall.length; i++) 
            redBall[i] = i + 1;   // 1--33 
 
        // used表示已经出现过的红球 ; boolean数组默认初始为false 
        boolean[] used = new boolean[redBall.length]; 
 
        int count = 0; //统计下注红球个数 
 
        // 输入6个不重复的红球号码,并存放到bet数组 
        //Scanner scan = null; 
        scan = new Scanner(System.in); 
        System.out.println("请输入6个红球号码(1-33):"); 
 
        while (scan.hasNext()) 
        { 
            int num = scan.nextInt(); // 获得输入 
             
            // 如果这个号码是1-33号,那么就重新选择 
            if (num < 1 || num > 33) 
            { 
                System.out.println("没有" 
                        + num + "号,请选1-33号。您还需要选择" 
                        + (6-count) +"个红球!"); 
                continue; 
            } 
            // 如果这个号码没有被选过,那么就放到bet数组 
            if (!used[num]) 
            { 
                betRedBall[count++] = num; 
                used[num] = true; 
                System.out.println("已选" 
                        + num + "号!您还需要选择" 
                        + (6-count) +"个红球!"); 
            } 
            else  
            { 
                System.out.println(num + "号已选过,您还需要选择" 
                        + (6-count) +"个红球!"); 
            } 
            // 选完6个红球则跳出循环 
            if (count==6) break; 
        } 
    } 
     
    // 从1-16中自选1个数字代表蓝球  
    public void seletBlueBall() 
    { 
        // 输入1个蓝球号码 
        //Scanner scan = null; 
        scan = new Scanner(System.in); 
        System.out.print("请输入1个蓝球号码(1-16):"); 
 
        while (scan.hasNextLine()) 
        { 
            int num = scan.nextInt(); // 获得输入 
            // 
            // 如果这个号码是1-16号,那么就重新选择 
            if (num < 1 || num > 16) 
            { 
                System.out.println("没有" + num + "号,请选1-16号!"); 
                continue; 
            } 
            else 
            { 
                betBlueBall = num; 
                System.out.println("已选" + num + "号!"); 
                break; 
            } 
        } 
    } 
 
    // 投注并开奖 
    public int lotteryBetting() 
    { 
        int correctRedCount = 0;          // 猜中的红球个数 
        boolean correctBlueCount = false; // 是否猜中篮球 
 
        //遍历选择的红球;对比开奖结果 算出中奖的红球个数 
        for (int i = 0; i < betRedBall.length; i++) 
        { 
            for (int j = 0; j < winningRedBall.length; j++) 
            { 
                if (betRedBall[i] == winningRedBall[j]) 
                { 
                     correctRedCount++; 
                     continue; 
                } 
            } 
        } 
 
        // 判断是否猜中蓝球 
        if (betBlueBall == winningBlueBall) correctBlueCount = true;  
 
        /**     没中奖  返回 0 
         *      一等奖  中 6+1 
         *      二等奖  中 6+0 
         *      三等奖  中 5+1 
         *      四等奖  中 5+0  中 4+1 
         *      五等奖  中 4+0  中 3+1 
         *      六等奖  中 2+1  中 0+1  中 1+1 
         */ 
        System.out.println("Debug:" 
                + correctRedCount + "," + correctBlueCount); 
        if (correctRedCount == 6) 
        { 
            if (correctBlueCount) return 1; 
            else return 2; 
        } 
        if (correctRedCount == 5) 
        { 
            if (correctBlueCount) return 3; 
            else return 4; 
        } 
        if (correctRedCount == 4) 
        { 
            if (correctBlueCount) return 4; 
            else return 5; 
        } 
        if (correctBlueCount) 
        { 
            if (correctRedCount == 3) return 5; 
            //else if (correctRedCount == 2) return 6; 
            //else if (correctRedCount == 1) return 6; 
            else  return 6; 
 
        } 
        return 0; 
    } 
} 
View Code

运行结果:
enter description here

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

-------------------------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 。

 

enter description here

 

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

 

enter description here

 

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

week7 Cylinder(二)

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

 

enter description here

 

7.1 Cylider.java

  1. package week7; 
  2.  
  3. import java.text.DecimalFormat; 
  4.  
  5. /** 
  6. * 7.1 创建 Cylinder类,以存储标签、半度; 
  7. * 方法包括获得及设置这些成员变量,计算直径、周长面积及体积。  
  8. */ 
  9. public class Cylinder 
  10. { 
  11. private String lable; //存储标签 
  12. private double radius; //圆柱半径 
  13. private double height; //圆柱的高 
  14. public Cylinder(String lable, double radius, double height) 
  15. { 
  16. this.lable = lable; 
  17. this.radius = radius; 
  18. this.height = height; 
  19. } 
  20.  
  21. public String getLable() 
  22. { 
  23. return lable; 
  24. } 
  25.  
  26. public boolean setLable(String lable) 
  27. { 
  28. boolean flag = true; 
  29.  
  30. if (lable.isEmpty()) flag = false; 
  31. else this.lable = lable.trim(); 
  32. //String.trim()截去字符串开头和末尾的空白 
  33. return flag; 
  34. } 
  35.  
  36. public double getRadius() 
  37. { 
  38. return radius; 
  39. } 
  40.  
  41. public void setRadius(double radius) 
  42. { 
  43. this.radius = radius; 
  44. } 
  45.  
  46. public double getHeight() 
  47. { 
  48. return height; 
  49. } 
  50.  
  51. public void setHeight(double height) 
  52. { 
  53. this.height = height; 
  54. } 
  55.  
  56. //返回圆柱底面直径 
  57. public double diameter() 
  58. { 
  59. return radius * 2; 
  60. } 
  61.  
  62. //返回圆柱底面周长 
  63. public double circumference() 
  64. { 
  65. return diameter() * Math.PI; 
  66. } 
  67.  
  68. //返回 表面积 = 圆柱底面积×2 + 底面周长×高 
  69. public double area() 
  70. { 
  71. return Math.PI * radius * radius * 2 
  72. + circumference() * height; 
  73. } 
  74.  
  75. //返回 圆柱底体积 
  76. public double volumn() 
  77. { 
  78. return Math.PI * radius * radius * height; 
  79. } 
  80.  
  81. @Override 
  82. public String toString() 
  83. { 
  84. String output = null; 
  85. DecimalFormat df = new DecimalFormat("#,##0.0##"); 
  86. output = lable 
  87. + " is a cylinder with radius = " + df.format(radius) 
  88. + " units and height = " + df.format(height) 
  89. + " units, " 
  90. + "\nwhich has diameter = " + df.format(diameter()) 
  91. + " units, circumference = " + df.format(circumference()) 
  92. + " units, " 
  93. + "\narea = " + df.format(area()) 
  94. + " square units, and volume = " + df.format(volumn()) 
  95. + " cubic units.\n"; 
  96. return output; 
  97. } 
  98.  
  99. public static void main(String[] args) 
  100. { 
  101. Cylinder c1 = new Cylinder("Small Example", 4.0, 10.0); 
  102. Cylinder c2 = new Cylinder("Medium Example", 22.1, 30.6); 
  103. Cylinder c3 = new Cylinder("Large Example", 100.0, 200.0); 
  104. c1.setLable(""); 
  105. System.out.println(c1); 
  106. System.out.println(c2); 
  107. System.out.println(c3); 
  108. } 
  109. } 
  110.  

7.2 CylinderList.java

  1. package week7; 
  2.  
  3. import java.text.DecimalFormat; 
  4. import java.util.ArrayList; 
  5.  
  6. /** 
  7. * 7.2 CylinderList类  
  8. */ 
  9. public class CylinderList 
  10. { 
  11. private String listName; 
  12. private ArrayList<Cylinder> cList; 
  13.  
  14. CylinderList(String listName, ArrayList<Cylinder> cList) 
  15. { 
  16. this.listName = listName; 
  17. this.cList = cList; 
  18. } 
  19.  
  20. //返回一个代表几何名字的字符串 
  21. public String getName() 
  22. { 
  23. return listName; 
  24. } 
  25.  
  26. //返回代表集合中Cylinder对象的个数 
  27. public int numberOfCylinders() 
  28. { 
  29. return cList.size(); 
  30. } 
  31.  
  32. //返回 所有的Cylinder对象的 高 的和 
  33. public double totalHeight() 
  34. { 
  35. double totalHeight = 0; 
  36. for (Cylinder cylinder : cList) 
  37. { 
  38. totalHeight += cylinder.getHeight(); 
  39. } 
  40. return totalHeight; 
  41. } 
  42.  
  43. //返回 所有的Cylinder对象的 圆柱底面直径 的和 
  44. public double totalDiameter() 
  45. { 
  46. double totalDiameter = 0; 
  47. for (Cylinder cylinder : cList) 
  48. { 
  49. totalDiameter += cylinder.diameter(); 
  50. } 
  51. return totalDiameter; 
  52. } 
  53.  
  54. //返回 所有的Cylinder对象的 面积 之和 
  55. public double totalArea() 
  56. { 
  57. double totalArea = 0; 
  58. for (Cylinder cylinder : cList) 
  59. { 
  60. totalArea += cylinder.area(); 
  61. } 
  62. return totalArea; 
  63. } 
  64.  
  65. //返回 所有的Cylinder对象的 体积 之和 
  66. public double totalVolume() 
  67. { 
  68. double totalVolume = 0; 
  69. for (Cylinder cylinder : cList) 
  70. { 
  71. totalVolume += cylinder.volumn(); 
  72. } 
  73. return totalVolume; 
  74. } 
  75.  
  76. //返回 所有的Cylinder对象 面积 的 平均值 
  77. public double averageArea() 
  78. { 
  79. double averageArea = 0; 
  80. if (cList.size()>0) 
  81. { 
  82. averageArea = totalArea()/cList.size(); 
  83. } 
  84. return averageArea; 
  85. } 
  86.  
  87. //返回 所有的Cylinder对象 体积 的 平均值 
  88. public double averageVolume() 
  89. { 
  90. double averageVolume = 0; 
  91. if (cList.size()>0) 
  92. { 
  93. averageVolume = totalVolume()/cList.size(); 
  94. } 
  95. return averageVolume; 
  96. } 
  97.  
  98. //返回 集合的名字及集合中每一个对象的toString方法 
  99. public String toString() 
  100. { 
  101. String output = "\n" + listName + "\n\n"; 
  102. for (Cylinder cylinder : cList) 
  103. { 
  104. output += (cylinder.toString() + "\n");  
  105. } 
  106. return output; 
  107. } 
  108.  
  109. //返回 集合的名字及Cylinder对象个数, 
  110. //总面积,总体积,平均面积及平均体积 
  111. public String summaryInfo() 
  112. { 
  113. String output = null; 
  114. DecimalFormat df = new DecimalFormat("#,##0.0##"); 
  115. output = "-----" + listName + " Summary-----" 
  116. + "\nNimber of Cylinders: " + numberOfCylinders() 
  117. + "\nTotal Area: " + df.format(totalArea()) 
  118. + "\nTotal Volume: " + df.format(totalVolume()) 
  119. + "\nTotal Height: " + df.format(totalHeight()) 
  120. + "\nTotal Diameter: " + df.format(totalDiameter()) 
  121. + "\nAverage Area: " + df.format(averageArea()) 
  122. + "\nAverage Volume: " + df.format(averageVolume()); 
  123. return output; 
  124. } 
  125. } 

7.3 CylinderListApp 测试类

  1. package week7; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileNotFoundException; 
  5. import java.util.ArrayList; 
  6. import java.util.Scanner; 
  7.  
  8. /** 
  9. * 7.3 CylinderListApp 测试类 
  10. * (a) 打开用户输入的文件并读取第一行作为集合的名字;之后读取其他行, 
  11. * 依次生成Cylinder对象,最后生成CylinderList对象。 
  12. * (b) 输出CylinderList对象(调用toString方法),之后空一行, 
  13. * (c) 输出CylinderList对象的汇总信息(调用summaryInfo方法) 
  14. * 注意: 
  15. * 1)如果输入文件名后出现错误称找不到文件,此时可输出绝对路径 
  16. * 2)读取文件第一行作为集合名称后,使用以scanFile.hasNext() 
  17. * 为条件的while循环反复读入三行,然后创建Cylinder对象 
  18. * 3)输出结果必须与下面测试输出的结果完全一致 
  19. */ 
  20. public class CyliderListApp 
  21. { 
  22. public static void main(String[] args) throws FileNotFoundException 
  23. { 
  24. String lable; 
  25. double radius; 
  26. double height; 
  27. Scanner scan0 = new Scanner(System.in); 
  28. Scanner scan1 = null; 
  29. Scanner inputStream = null; 
  30.  
  31. ArrayList<Cylinder> cList = new ArrayList<>(10); 
  32. CylinderList cylinderList = null;//new CylinderList(listName, cList) 
  33.  
  34. System.out.print("Enter file name: "); 
  35. String fileName = scan0.nextLine(); // cylinder_0.dat 
  36. scan0.close(); 
  37.  
  38. File file = new File("resource/" + fileName); 
  39. if(file.exists()) 
  40. { 
  41. inputStream = new Scanner(file); 
  42.  
  43. String listName = inputStream.nextLine(); 
  44. while (inputStream.hasNextLine()) 
  45. { 
  46. String line = inputStream.nextLine(); 
  47. //使用逗号分隔line,例:Small Example, 4.0, 10.0 
  48. scan1 = new Scanner(line); 
  49. scan1.useDelimiter(","); 
  50. if (scan1.hasNext()) 
  51. { 
  52. lable = scan1.next(); 
  53. radius = Double.parseDouble(scan1.next()); 
  54. height = Double.parseDouble(scan1.next()); 
  55. //创建Cylinder对象并加入ArrayList<Cylinder>中 
  56. cList.add(new Cylinder(lable, radius, height)); 
  57. } 
  58. scan1.close(); //就近原则,以免出现空指针 
  59. } 
  60. inputStream.close(); 
  61. //初始化CylinderList对象 
  62. cylinderList = new CylinderList(listName, cList); 
  63. System.out.print(cylinderList.toString()); 
  64. System.out.println(cylinderList.summaryInfo()); 
  65. } 
  66. else 
  67. { 
  68. System.out.println(file.getAbsolutePath()); 
  69. } 
  70. } 
  71. } 
  72.  

运行结果:

 

enter description here

 

 

enter description here

 

week8 Cylinder(三)

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

8.1 Cylider.java

导入使用的是7.1的Cylinder 类

8.2 CylinderList.java

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

  1. package week8; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileNotFoundException; 
  5. import java.text.DecimalFormat; 
  6. import java.util.ArrayList; 
  7. import java.util.Scanner; 
  8.  
  9. import week7.Cylinder; 
  10.  
  11. /** 
  12. * 8.2 同7.2 CylinderList类,只是增加了4个方法 
  13. */ 
  14. public class CylinderList 
  15. { 
  16. private String listName = null; 
  17. private Scanner scan = null; 
  18. private Scanner inputStream = null;  
  19. private ArrayList<Cylinder> cList = null; 
  20.  
  21. /** 
  22. *  
  23. * @param listName 
  24. * @param cList 
  25. */ 
  26. CylinderList(String listName, ArrayList<Cylinder> cList) 
  27. { 
  28. this.listName = listName; 
  29. this.cList = cList; 
  30. } 
  31. /***************************以下为新增方法***********************************/ 
  32. /** 
  33. * 接收一个代表文件名字的字符串参数,读入文件内容将其存储到集合名字变量及 ArrayList类型的集合变量中; 
  34. * 利用集合名字及集合变量生成 CylinderList对象;最后返回该 CylinderList对象; 
  35. * @param fileName 
  36. * @return 
  37. * @throws FileNotFoundException 
  38. */ 
  39. public CylinderList readFile(String fileName) throws FileNotFoundException 
  40. { 
  41. CylinderList cylinderList = null; 
  42. String lable;  
  43. double radius;  
  44. double height; 
  45. String nameList = null; 
  46.  
  47. //读文件并赋值 
  48. File file = new File(fileName);  
  49. if(file.exists())  
  50. {  
  51. inputStream = new Scanner(file);  
  52.  
  53. nameList = inputStream.nextLine();  
  54. while (inputStream.hasNextLine())  
  55. {  
  56. String line = inputStream.nextLine();  
  57. //使用逗号分隔line,例:Small Example, 4.0, 10.0  
  58. scan = new Scanner(line);  
  59. scan.useDelimiter(",");  
  60. if (scan.hasNext())  
  61. {  
  62. lable = scan.next();  
  63. radius = Double.parseDouble(scan.next());  
  64. height = Double.parseDouble(scan.next());  
  65. //创建Cylinder对象并加入ArrayList<Cylinder>中  
  66. cList.add(new Cylinder(lable, radius, height));  
  67. } 
  68. } 
  69. cylinderList = new CylinderList(nameList, cList); 
  70. }  
  71. else  
  72. {  
  73. System.out.println(file.getAbsolutePath());  
  74. System.out.println(fileName + " not exists!"); 
  75. } 
  76.  
  77. return cylinderList; 
  78. } 
  79.  
  80. /** 
  81. * 添加一个Cylinder对象到CylinderList对象中 
  82. * @param label 
  83. * @param radius 
  84. * @param height 
  85. */ 
  86. public void addCylinder(String label, double radius, double height) 
  87. { 
  88. cList.add(new Cylinder(label, radius, height)); 
  89. } 
  90.  
  91. /** 
  92. * 接收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象,则返回该对象并删除之; 
  93. * 否则返回 null; 
  94. * @param label 
  95. * @return 
  96. */ 
  97. public Cylinder deleteCylinder(String label) 
  98. { 
  99. Cylinder cylinder = null; 
  100. for (int i = 0; i < cList.size(); i++) 
  101. { 
  102. //如果找到 先赋值 后 删除 
  103. if (cList.get(i).getLable().equalsIgnoreCase(label) == true) 
  104. { 
  105. cylinder = cList.get(i); 
  106. cList.remove(i); 
  107. } 
  108. } 
  109. return cylinder; 
  110. } 
  111.  
  112. /** 
  113. * 参数接收收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象, 
  114. * 则返回该对象;否则返回 null; 
  115. * @param label 
  116. * @return 
  117. */ 
  118. public Cylinder findCylinder(String label) 
  119. { 
  120. Cylinder cylinder = null; 
  121. for (int i = 0; i < cList.size(); i++) 
  122. { 
  123. //如果找到 赋值 
  124. if (cList.get(i).getLable().equalsIgnoreCase(label) == true) 
  125. { 
  126. cylinder = cList.get(i); 
  127. } 
  128. } 
  129. return cylinder; 
  130. } 
  131. /** 
  132. * String类中两个方法的比较: 
  133. * equals:将此字符串与指定的对象比较。当且仅当该参数不为 null, 
  134. * 并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。  
  135. * equalsIgnoreCase:将此 String 与另一个 String 比较,不考虑大小写。如果两个字符串的长度相同, 
  136. * 并且其中的相应字符都相等(忽略大小写),则认为这两个字符串是相等的。  
  137. */ 
  138. /***************************以上为新增方法*********************************/ 
  139.  
  140. .... 
  141. } 

8.3 CylinderListMenuApp.java

  1. package week8; 
  2.  
  3. import java.io.IOException; 
  4. import java.util.ArrayList; 
  5. import java.util.Scanner; 
  6.  
  7. import week7.Cylinder; 
  8.  
  9. /** 
  10. * 8.3 CylinderListMenuApp 
  11. * 包含 main 方法,呈现有 7 个选项的菜单 
  12. * (1) 读入文件内容并创建 CylinderList对象 
  13. * (2) 打印输出 CylinderList对象 
  14. * (3) 打印输出 CylinderList对象的汇总信息 
  15. * (4) 增加一个 CylinderList对象至 CylinderList对象中 
  16. * (5) 从 CylinderList对象中删除一个 Cylinder对象 
  17. * (6) 在 CylinderList对象中找到一个 Cylinder对象 
  18. * (7) 退出程序 
  19. * 设计: 
  20. * main方法中将先输出带有描述的 7个选项信息。 
  21. * 一旦用户输入了一个选项编号,则对应 的方法将被调用。 
  22. * 之后再次呈现选项信息,提示用户进行选择。 
  23. */ 
  24. public class CylinderListMenuApp 
  25. { 
  26. /** 
  27. * 显示菜单信息 
  28. */ 
  29. private static void showMenu() 
  30. { 
  31. //输出带有描述的 7个选项信息 
  32. System.out.println("Cylinder List System Menu"); 
  33. System.out.println("R - ReadFile and Create Cylinder List"); 
  34. System.out.println("P - Print Cylinder List"); 
  35. System.out.println("S - Print Summary"); 
  36. System.out.println("A - Add Cylinder"); 
  37. System.out.println("D - Delete Cylinder"); 
  38. System.out.println("F - Find Cylinder"); 
  39. System.out.println("Q - Quit"); 
  40. } 
  41.  
  42. public static void main(String[] args) throws IOException 
  43. { 
  44. //创建一个 Cylinder集合 
  45. ArrayList<Cylinder> clist = new ArrayList<>(); 
  46.  
  47. String sName = "***no list name assigned***"; 
  48. CylinderList cylinderList = new CylinderList(sName, clist); 
  49.  
  50.  
  51. Scanner scan = new Scanner(System.in); 
  52. char key; //输入的key值 
  53.  
  54. showMenu(); //显示提示菜单 
  55. while (true) 
  56. { 
  57. //提示用户进行选择 
  58. System.out.print("\nEnter Code [R, P, S, A, D, F or Q]: "); 
  59.  
  60. key = scan.nextLine().charAt(0); 
  61. switch (key) 
  62. { 
  63. case 'r'://resource/cylinder_1.dat 
  64. case 'R'://ReadFile and Create Cylinder List 
  65. System.out.print("\tFile name: "); 
  66. //读文件转化为CylinderList对象后重新赋值 
  67. cylinderList = cylinderList.readFile(scan.nextLine()); 
  68. System.out.println("\tFile read in and Cylinder List created"); 
  69. break; 
  70. case 'p': 
  71. case 'P'://Print Cylinder List 
  72. System.out.println(cylinderList); 
  73. break; 
  74. case 's': 
  75. case 'S'://Print Summary 
  76. System.out.println(cylinderList.summaryInfo()); 
  77. break; 
  78. case 'a': 
  79. case 'A'://Add Cylinder 
  80. System.out.print("\tLabel: "); 
  81. String labelA = scan.nextLine(); 
  82. System.out.print("\tRadius: "); 
  83. double radius = Double.parseDouble(scan.nextLine()); 
  84. System.out.print("\tHeight: "); 
  85. double height =Double.parseDouble(scan.nextLine()); 
  86. cylinderList.addCylinder(labelA, radius, height); 
  87. System.out.println("\t*** Cylinder added ***"); 
  88. break; 
  89. case 'd': 
  90. case 'D'://Delete Cylinder 
  91. System.out.print("\tLabel: "); 
  92. String labelD = scan.nextLine(); 
  93. if(cylinderList.deleteCylinder(labelD) == null) 
  94. System.out.println("\t\"" + labelD + "\" not found"); 
  95. else 
  96. System.out.println("\t\"" + labelD +"\" deleted"); 
  97. break; 
  98. case 'f': 
  99. case 'F'://Find Cylinder 
  100. System.out.print("\tLabel: "); 
  101. String labelF = scan.nextLine(); 
  102. if(cylinderList.findCylinder(labelF) == null) 
  103. System.out.println("\t\"" + labelF + "\" not found"); 
  104. else 
  105. System.out.println(cylinderList.findCylinder(labelF)); 
  106. break; 
  107. case 'q': 
  108. case 'Q'://Quit 
  109. return; 
  110. default: 
  111. System.out.println("\t*** invalid code ***"); 
  112. } 
  113. } 
  114. } 
  115. } 

运行演示:

 

week8

 

week10 继承特性的练习: 货物

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

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

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

  •  

    enter description here

     

10.1 InventoryItem.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.1 InventoryItem.java 
  5. * 货物类:所有物品类的基类 
  6. */ 
  7. public class InventoryItem 
  8. { 
  9. protected String name; 
  10. protected double price; 
  11. private static double taxRate = 0; 
  12.  
  13. public static void main(String[] args) 
  14. { 
  15. InventoryItem.setTaxRate(0.08); 
  16. InventoryItem item1 = new InventoryItem("Birdseed", 7.99); 
  17. InventoryItem item2 = new InventoryItem("Picture", 10.99); 
  18.  
  19. System.out.println(item1); 
  20. System.out.println(item2); 
  21. } 
  22.  
  23. /** 
  24. * 初始化 
  25. * @param name 
  26. * @param price 
  27. */ 
  28. public InventoryItem(String name, double price) 
  29. { 
  30. this.name = name; 
  31. this.price = price; 
  32. } 
  33.  
  34. @Override 
  35. public String toString() 
  36. { 
  37. return name + ": $" + calculateCost(); 
  38. } 
  39.  
  40. /** 
  41. * 货物含税的价格 
  42. * @return 
  43. */ 
  44. public double calculateCost() 
  45. { 
  46. return this.price * (1 + taxRate); 
  47. } 
  48.  
  49. public String getName() 
  50. { 
  51. return name; 
  52. } 
  53.  
  54. /** 
  55. * 设置税率; 
  56. * 静态方法不能使用隐含(或明确的把this作为其调用对象) 的实例变量(或非静态方法) 
  57. * @param taxRateIn 
  58. */ 
  59. public static void setTaxRate(double taxRateIn) 
  60. { 
  61. taxRate = taxRateIn; 
  62. } 
  63. } 

运行结果:
enter description here

10.2 ElectronicsItem.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.2 ElectronicsItem.java 
  5. * 电子货物类:InventoryItem的派生类 
  6. */ 
  7. public class ElectronicsItem extends InventoryItem 
  8. { 
  9. protected double weight; //电子货物重量 
  10. public static final double SHIPPING_COST = 1.5;//每磅的货运费用 
  11.  
  12. public ElectronicsItem(String name, double price, double weight) 
  13. { 
  14. super(name, price); 
  15. this.weight = weight; 
  16. } 
  17.  
  18. @Override 
  19. public double calculateCost() 
  20. { 
  21. return super.calculateCost() + weight * SHIPPING_COST; 
  22. } 
  23.  
  24. public static void main(String[] args) 
  25. { 
  26. InventoryItem.setTaxRate(0.08); 
  27. ElectronicsItem eItem = new ElectronicsItem("Monitor", 100, 10.0); 
  28. System.out.println(eItem); 
  29. } 
  30. } 
  31.  

运行结果:
enter description here

10.3 OnlineTextItem.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.3 OnlineTextItem.java 
  5. * 在线文本商品类:InventoryItem的派生类 
  6. * 该类代表用户可购买的在线文本商品(如电子书或者电子杂志); 
  7. * 因为它只是概念级的、 代表物品的类,因此可以设置为抽象类; 
  8. */ 
  9. public abstract class OnlineTextItem extends InventoryItem 
  10. { 
  11.  
  12. public OnlineTextItem(String name, double price) 
  13. { 
  14. super(name, price); 
  15. // TODO Auto-generated constructor stub 
  16. } 
  17.  
  18. @Override 
  19. public double calculateCost() 
  20. { 
  21. return price; 
  22. } 
  23.  
  24. } 
  25.  

10.4 OnlineArticle.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.4 OnlineArticle.java 
  5. * 电子类文本物品:OnlineTextItem的派生类 
  6. */ 
  7. public class OnlineArticle extends OnlineTextItem 
  8. { 
  9. private int wordCount; //记录字数 
  10.  
  11. public OnlineArticle(String name, double price) 
  12. { 
  13. super(name, price); 
  14. this.wordCount = 0; 
  15. } 
  16.  
  17. @Override 
  18. public String toString() 
  19. { 
  20. return name + ": $"+ price  
  21. + " " + this.wordCount;  
  22. } 
  23.  
  24. public void setWordCount(int wordCount) 
  25. { 
  26. this.wordCount = wordCount; 
  27. } 
  28.  
  29. } 
  30.  

10.5 OnlineBook.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.5 OnlineBook.java 
  5. * 电子书:OnlineTextItem的派生类 
  6. */ 
  7. public class OnlineBook extends OnlineTextItem 
  8. { 
  9. protected String author; //电子书作者 
  10.  
  11. public OnlineBook(String name, double price) 
  12. { 
  13. super(name, price); 
  14. author = "Author Not Listed"; 
  15. } 
  16.  
  17. public void setAuthor(String author) 
  18. { 
  19. this.author = author; 
  20. } 
  21.  
  22. @Override 
  23. public String toString() 
  24. { 
  25. return name + " - " 
  26. + author +": $" + price; 
  27. } 
  28.  
  29. public static void main(String[] args) 
  30. { 
  31. OnlineBook book = new OnlineBook("A Novel Novel", 9.99); 
  32. System.out.println(book); 
  33.  
  34. book.setAuthor("Jane Lane"); 
  35. System.out.println(book); 
  36. } 
  37.  
  38. } 
  39.  

运行结果:
enter description here

10.6 InventoryApp.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.6 InventoryApp.java 
  5. * 测试类: 
  6. * (1) 设置税率为 0.05 
  7. * (2) 初始化并输出 4个对象(item1、item2、item3、item4) 
  8. */ 
  9. public class InventoryApp 
  10. { 
  11. public static void main(String[] args) 
  12. { 
  13. InventoryItem.setTaxRate(0.05); 
  14.  
  15. InventoryItem item1 = new InventoryItem("pen", 25); 
  16. ElectronicsItem item2 = new ElectronicsItem("apple phone", 1000, 1.8); 
  17. OnlineArticle item3 = new OnlineArticle("Java", 8.5); 
  18. OnlineBook item4 = new OnlineBook("Head first Java", 40); 
  19.  
  20. item3.setWordCount(700); 
  21. item4.setAuthor("Kathy&Bert"); 
  22.  
  23. System.out.println(item1); 
  24. System.out.println(item2); 
  25. System.out.println(item3); 
  26. System.out.println(item4); 
  27.  
  28. System.out.println("All inventory:\n\n" + myItems); 
  29. System.out.println("Total: " + myItems.calculateTotal(2)); 
  30. } 
  31. } 
  32.  

运行结果:
enter description here

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

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

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

 

enter description here

 

11.7 ItemsList.java

  1. package week11; 
  2.  
  3. import week10.ElectronicsItem; 
  4. import week10.InventoryItem; 
  5.  
  6. /** 
  7. * 11.7 ItemsList.java 
  8. * 存放InventoryItem对象的数组 
  9. */ 
  10. public class ItemsList 
  11. { 
  12. private InventoryItem[] inventory; 
  13. private int count; 
  14.  
  15. public ItemsList() 
  16. { 
  17. inventory = new InventoryItem[20]; 
  18. count = 0; 
  19. } 
  20.  
  21. /** 
  22. * 增加一个item 
  23. * @param itemIn 
  24. */ 
  25. public void addItem(InventoryItem itemIn) 
  26. { 
  27. this.inventory[count++] = itemIn; 
  28. } 
  29.  
  30. /** 
  31. * 返回代表数组各元素价格的总和 
  32. * @param electronicsSurcharge,代表征收ElectronicsItem的附加费 
  33. * @return 
  34. */ 
  35. public double calculateTotal(double electronicsSurcharge) 
  36. { 
  37. double totalCost = 0; 
  38.  
  39. /** 需要遍历 inventory数组的每一个元素,将价格 (cost)累加到和上。 
  40. * 如果元素为 ElectronicsItem类的引用变量 ,则激活calculateCost方法, 
  41. * 增加该的 方法的electronicsSurcharge 
  42. */ 
  43. for (int i = 0; i < count; i++) 
  44. { 
  45. if (inventory[i] instanceof ElectronicsItem) 
  46. { 
  47. totalCost += inventory[i].calculateCost() + electronicsSurcharge; 
  48. } 
  49. else 
  50. { 
  51. totalCost += inventory[i].calculateCost(); 
  52. } 
  53.  
  54. } 
  55. return totalCost; 
  56. } 
  57.  
  58. @Override 
  59. public String toString() 
  60. { 
  61. String output = ""; 
  62. for (int i = 0; i < count; i++) 
  63. { 
  64. output += inventory[i].toString(); 
  65. output += "\n"; 
  66. } 
  67. return output; 
  68. } 
  69. } 

11.8 ItemsListApp.java

  1. package week11; 
  2.  
  3. import week10.ElectronicsItem; 
  4. import week10.InventoryItem; 
  5. import week10.OnlineArticle; 
  6. import week10.OnlineBook; 
  7.  
  8. /** 
  9. * 11.8 ItemsListApp.java 测试类 
  10. */ 
  11. public class ItemListApp 
  12. { 
  13. public static void main(String[] args) 
  14. { 
  15. // a)初始化名为myItems的ItemsList对象 
  16. ItemsList myItems = new ItemsList(); 
  17.  
  18. // b)通过InventoryItem的setTaxRate方法设置税率为 0.05 
  19. InventoryItem.setTaxRate(0.05); 
  20.  
  21. // c)初始化以下4个货物并将其增加到myItems中 
  22. ElectronicsItem electItem = new ElectronicsItem("笔记本", 1234.56, 10); 
  23. InventoryItem item = new InventoryItem("机油", 9.8); 
  24. OnlineBook book = new OnlineBook("疯狂Java讲义", 12.3); 
  25. book.setAuthor("李刚"); 
  26. OnlineArticle article = new OnlineArticle("如何学好Java", 3.4); 
  27. article.setWordCount(700); 
  28.  
  29. myItems.addItem(electItem); 
  30. myItems.addItem(item); 
  31. myItems.addItem(book); 
  32. myItems.addItem(article); 
  33.  
  34. System.out.println("All inventory:\n\n" + myItems); 
  35.  
  36. System.out.println("Total: " + myItems.calculateTotal(1.215)); 
  37. } 
  38.  
  39. } 

运行结果:
enter description here

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

-------------------------2016-12-20更新
enter description here

小变动:

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

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

重难点:

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

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

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

 

enter description here

 

12.1 旅程类:Itinerary

  1. package week12; 
  2.  
  3. /** 
  4. * 12.1 旅程类 
  5. */ 
  6. public class Itinerary 
  7. { 
  8. private String formAirport; 
  9. private String toAirport; 
  10. private String depDateTime; 
  11. private String arrDateTime; 
  12. private int miles; 
  13.  
  14. public Itinerary 
  15. (String formAirport,String toAirport,String depDateTime,String arrDateTime,int miles) 
  16. { 
  17. this.formAirport = formAirport; 
  18. this.toAirport = toAirport; 
  19. this.depDateTime = depDateTime; 
  20. this.arrDateTime = arrDateTime; 
  21. this.miles = miles; 
  22. } 
  23.  
  24. public String getDepDateTime() 
  25. { 
  26. return depDateTime; 
  27. } 
  28.  
  29. public String getArrDateTime() 
  30. { 
  31. return arrDateTime; 
  32. } 
  33.  
  34. public int getMiles() 
  35. { 
  36. return miles; 
  37. } 
  38.  
  39. @Override 
  40. public String toString() 
  41. { 
  42. String output = "" 
  43. + "" + formAirport 
  44. + "-" + toAirport 
  45. + " (" + depDateTime 
  46. + " - " + arrDateTime 
  47. + ")" 
  48. + " " + miles; 
  49. return output; 
  50. } 
  51. } 

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

  1. package week12; 
  2.  
  3. import java.text.DecimalFormat; 
  4. import java.text.Format; 
  5.  
  6. /** 
  7. * 12.2 飞机票(抽象)基类 
  8. */ 
  9. public abstract class AirTicket implements Comparable<AirTicket> 
  10. { 
  11. private String flightNum; //航班号 
  12. private Itinerary itinerary; //行程 
  13. private double baseFare; //飞机票基本费用 
  14. private double fareAdjustmentFactor; //费用调整因素 
  15.  
  16. public AirTicket(String flightNum,Itinerary itinerary,double baseFare,double fareAdjustmentFactor) 
  17. { 
  18. this.flightNum = flightNum; 
  19. this.itinerary = itinerary; 
  20. this.baseFare = baseFare; 
  21. this.fareAdjustmentFactor = fareAdjustmentFactor; 
  22. } 
  23.  
  24. public String getFlightNum() 
  25. { 
  26. return flightNum; 
  27. } 
  28.  
  29. public Itinerary getItinerary() 
  30. { 
  31. return itinerary; 
  32. } 
  33.  
  34. public double getBaseFare() 
  35. { 
  36. return baseFare; 
  37. } 
  38.  
  39. public double getFareAdjustmentFactor() 
  40. { 
  41. return fareAdjustmentFactor; 
  42. } 
  43.  
  44. /** 
  45. * 自然比较方法:(忽略大小写)比较航班号 
  46. * @return 该对象小于、等于或大于指定对象 at,分别返回负整数、零或正整数。  
  47. */ 
  48. @Override 
  49. public int compareTo(AirTicket at) 
  50. { 
  51. return flightNum.compareToIgnoreCase(at.flightNum); 
  52. } 
  53.  
  54. @Override 
  55. public String toString() 
  56. { 
  57. Format formater = new DecimalFormat("###,###.00"); 
  58. String output = "" 
  59. + "\nFlight: " + flightNum 
  60. + "\n" + itinerary 
  61. + " (" + totalAwardMiles() + " award miles)" 
  62. + "\nBase Fare: $" + formater.format(baseFare) 
  63. + " Fare Adjustment Factor: " + fareAdjustmentFactor 
  64. + "\nTotal Fare: $" + formater.format(totalFare()) 
  65. + "\t"; 
  66. return output; 
  67. } 
  68.  
  69. public abstract double totalFare(); 
  70.  
  71. public abstract double totalAwardMiles(); 
  72.  
  73. } 

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.3 飞机票子类---经济舱机票 
  5. */ 
  6. public class Economy extends AirTicket 
  7. { 
  8. private final static double AWARDMILESFACTOR = 1.5; 
  9.  
  10. public Economy(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor) 
  11. { 
  12. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 
  13. } 
  14.  
  15. @Override 
  16. public double totalFare() 
  17. { 
  18. return super.getBaseFare() * super.getFareAdjustmentFactor(); 
  19. } 
  20.  
  21. @Override 
  22. public double totalAwardMiles() 
  23. { 
  24. return super.getItinerary().getMiles() * AWARDMILESFACTOR; 
  25. } 
  26.  
  27. @Override 
  28. public String toString() 
  29. { 
  30. return super.toString() + " (class Economy)\n " 
  31. + "Includes Award Miles Factor: " 
  32. + AWARDMILESFACTOR; 
  33. } 
  34. } 

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.4 飞机票子类---商务舱机票 
  5. */ 
  6. public class Business extends AirTicket 
  7. { 
  8. private final static double AWARDMILESFACTOR = 2; //这里我改为2(题目为1.5) 
  9. private double foodAndBeverages; 
  10. private double entertaiment; 
  11.  
  12. public Business(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  13. double foodAndBeverages, double entertaiment) 
  14. { 
  15. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 
  16. this.foodAndBeverages = foodAndBeverages; 
  17. this.entertaiment = entertaiment; 
  18. } 
  19.  
  20. @Override 
  21. public double totalFare() 
  22. { 
  23. return super.getBaseFare() * super.getFareAdjustmentFactor() 
  24. + foodAndBeverages + entertaiment; 
  25. } 
  26.  
  27. @Override 
  28. public double totalAwardMiles() 
  29. { 
  30. return super.getItinerary().getMiles() * AWARDMILESFACTOR; 
  31. } 
  32.  
  33. @Override 
  34. public String toString() 
  35. { 
  36. return super.toString()+ " (class Business)\n " 
  37. + "Includes Food/Beverage: $" + foodAndBeverages 
  38. + " Entertaiment: $" + entertaiment; 
  39. } 
  40.  
  41. } 

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.5 飞机票子类---不可退的机票 
  5. */ 
  6. public class NonRefundable extends AirTicket 
  7. { 
  8. private double discountFactor; 
  9.  
  10. public NonRefundable(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  11. double discountFactor) 
  12. { 
  13. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 
  14. this.discountFactor = discountFactor; 
  15. } 
  16. @Override 
  17. public double totalFare() 
  18. { 
  19. return super.getBaseFare() * super.getFareAdjustmentFactor() 
  20. * discountFactor; 
  21. } 
  22.  
  23. @Override 
  24. public double totalAwardMiles() 
  25. { 
  26. return super.getItinerary().getMiles(); 
  27. } 
  28.  
  29. @Override 
  30. public String toString() 
  31. { 
  32. return super.toString()+ " (class NonRefundable)\n " 
  33. + "Includes DiscountFactor: " 
  34. + discountFactor; 
  35. } 
  36. } 

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.6 飞机票子类---商务舱机票子类---精英类机票 
  5. */ 
  6. public class Elite extends Business 
  7. { 
  8. private double cService; 
  9.  
  10. public Elite(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  11. double foodAndBeverages, double entertaiment, double cService) 
  12. { 
  13. super(flightNum, itinerary, baseFare, fareAdjustmentFactor, foodAndBeverages, entertaiment); 
  14. this.cService = cService; 
  15. } 
  16.  
  17. @Override 
  18. public double totalFare() 
  19. { 
  20. return super.totalFare() + cService; 
  21. } 
  22.  
  23. @Override 
  24. public double totalAwardMiles() 
  25. { 
  26. return super.totalAwardMiles(); 
  27. } 
  28.  
  29. @Override 
  30. public String toString() 
  31. { 
  32. return super.toString()+ " \n " 
  33. + "Includes: Comm Services: $" + cService; 
  34. } 
  35. } 

12.7 测试类: AirTicketProcessor

  1. package week12; 
  2.  
  3. import java.util.Arrays; 
  4.  
  5. /** 
  6. * 12.7 测试类 
  7. */ 
  8. public class AirTicketProcessor 
  9. { 
  10. public static void main(String[] args) 
  11. { 
  12. AirTicket[] airTickets = new AirTicket[4]; //四张 飞机票 
  13. Itinerary trip; // 临时行程对象 
  14.  
  15. // 初始化 题目给出的 四张票 
  16. trip = new Itinerary("ATL", "LGA", "2015/05/01 1500", "2015/05/01 1740", 800); 
  17. Economy economy = new Economy("DL 1867", trip, 450, 1); 
  18. trip = new Itinerary("ATL", "LGA", "2015/05/01 1400", "2015/05/01 1640", 800); 
  19. Business business = new Business("DL 1865", trip, 450, 2, 50, 50); 
  20. trip = new Itinerary("ATL", "LGA", "2015/05/01 0900", "2015/05/01 1140", 800); 
  21. Elite elite = new Elite("DL 1863", trip, 450, 2.5, 50, 50, 100); 
  22. trip = new Itinerary("ATL", "LGA", "2015/05/01 0800", "2015/05/01 1040", 800); 
  23. NonRefundable nonRefundable = new NonRefundable("DL 1861", trip, 450, 0.45, 0.9); 
  24.  
  25. // 将这4个对象添加到 airTickets  
  26. airTickets[0] = (economy); 
  27. airTickets[1] = (business); 
  28. airTickets[2] = (elite); 
  29. airTickets[3] = (nonRefundable); 
  30.  
  31. //输出报告 
  32. System.out.println("----------Air Ticket Report-----------"); 
  33. for (int i = 0; i < airTickets.length; i++) 
  34. System.out.println(airTickets[i]); 
  35.  
  36. Arrays.sort(airTickets); // 按航班号排序并输出报告 
  37. System.out.println("\n----------Air Ticket Report (by Flight Number)-----------"); 
  38. for (int i = 0; i < airTickets.length; i++) 
  39. System.out.println(airTickets[i]); 
  40. } 
  41. } 

运行结果:

 

enter description here

 

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下,如下所示:

 

enter description here

 

  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.  
  3. import java.io.BufferedReader; 
  4. import java.io.File; 
  5. import java.io.FileReader; 
  6. import java.io.IOException; 
  7. import java.util.Arrays; 
  8.  
  9. import week12.AirTicket; 
  10. import week12.Business; 
  11. import week12.Economy; 
  12. import week12.Elite; 
  13. import week12.Itinerary; 
  14. import week12.NonRefundable; 
  15.  
  16. /** 
  17. * 13.8 该类完成从数据文件中读取数据并声称报告的功能 
  18. */ 
  19. public class AirTicketProcessor 
  20. { 
  21. private AirTicket[] Tickets; 
  22. private String[] invalidRecords; 
  23.  
  24. public AirTicketProcessor() 
  25. { 
  26. Tickets = new AirTicket[0]; 
  27. invalidRecords = new String[0]; 
  28. } 
  29.  
  30. /** 
  31. * 以行为单位读取文件,常用于读面向行的格式化文件 (注意:这个读取文件并分割参数的方法没有使用题目给出的方法) 
  32. */ 
  33. public void readAirTicketFile(String fileName) 
  34. { 
  35. // 这里我设置为 工程 目录的 resource 下 
  36. String path = "resource/" + fileName; 
  37. File file = new File(path); 
  38.  
  39. BufferedReader reader = null; 
  40. try 
  41. { 
  42. reader = new BufferedReader(new FileReader(file)); 
  43. String tempString = null; // 每行的字符串临时变量 
  44. // 一次读入一行,直到读入null为文件结束 
  45. while ((tempString = reader.readLine()) != null) 
  46. { 
  47. try 
  48. { 
  49. String[] lineArr = tempString.split(","); 
  50. // 以 逗号 为分隔符, 并添加 票据信息 
  51. switch (lineArr[0]) 
  52. { 
  53. case "N": 
  54. addAirTicket(new NonRefundable(lineArr[1], 
  55. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  56. Integer.parseInt(lineArr[6])), 
  57. Integer.parseInt(lineArr[7]), Double.parseDouble(lineArr[8]), 
  58. Double.parseDouble(lineArr[9]))); 
  59. break; 
  60. case "E": 
  61. addAirTicket(new Economy(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. break; 
  66. case "B": 
  67. addAirTicket(new Business(lineArr[1], 
  68. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  69. Integer.parseInt(lineArr[6])), 
  70. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 
  71. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]))); 
  72. break; 
  73. case "F": 
  74. addAirTicket(new Elite(lineArr[1], 
  75. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  76. Integer.parseInt(lineArr[6])), 
  77. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 
  78. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]), 
  79. Double.parseDouble(lineArr[11]))); 
  80. break; 
  81. default: 
  82. addInvaildRecord(tempString); 
  83. break; 
  84. } 
  85. } catch (Exception e) 
  86. { 
  87. System.out.println("Line string split error!"); 
  88. } 
  89. } 
  90. } catch (IOException e) 
  91. { 
  92. System.out.println("Not find AirTicketFile!"); 
  93. // e.printStackTrace(); 
  94. } finally 
  95. { 
  96. if (reader != null) 
  97. { 
  98. try 
  99. { 
  100. reader.close(); 
  101. } catch (IOException e1) 
  102. { 
  103. } 
  104. } 
  105. } 
  106. } 
  107.  
  108. /** 
  109. * 将AirTicket类数组的长度增加1,之后将传入的对象放入数组中 
  110. *  
  111. * @param airTicket 
  112. */ 
  113. public void addAirTicket(AirTicket airTicket) 
  114. { 
  115. Tickets = Arrays.copyOf(Tickets, Tickets.length + 1); 
  116. Tickets[Tickets.length - 1] = (airTicket); 
  117. } 
  118.  
  119. /** 
  120. * 将invalidRecords数组的长度增加1,将传入的字符串放入数组中(每一行以代表机票种类的 字符开头(N, E, B和F是合法的机票种类), 
  121. * 如果开头字母不在此范围中,则此行为不合法记录) 
  122. *  
  123. * @param lineStr 
  124. */ 
  125. public void addInvaildRecord(String lineStr) 
  126. { 
  127. invalidRecords = Arrays.copyOf(invalidRecords, invalidRecords.length + 1); 
  128. invalidRecords[invalidRecords.length - 1] = (lineStr); 
  129. } 
  130.  
  131. /** 
  132. * 返回 AirTickets报告 
  133. */ 
  134. public String generateReport() 
  135. { 
  136. String output = ""; 
  137. for (AirTicket airTicket : Tickets) 
  138. { 
  139. output += airTicket + "\n"; 
  140. } 
  141. return output; 
  142. } 
  143.  
  144. /** 
  145. * 以航班号的升序 返回AirTickets报告 
  146. */ 
  147. public String generateReportByFlightNum() 
  148. { 
  149. String output = ""; 
  150.  
  151. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 
  152. Arrays.sort(orderT); 
  153.  
  154. for (AirTicket airTicket : orderT) 
  155. { 
  156. output += airTicket + "\n"; 
  157. } 
  158. return output; 
  159. } 
  160.  
  161. /** 
  162. * 以行程的升序 返回AirTickets报告 
  163. */ 
  164. public String generateReportByItinerary() 
  165. { 
  166. String output = ""; 
  167.  
  168. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 
  169. Arrays.sort(orderT, new ItineraryCompare()); 
  170.  
  171. for (AirTicket airTicket : orderT) 
  172. { 
  173. output += airTicket + "\n"; 
  174. } 
  175. return output; 
  176. } 
  177. } 

13.9 自定义排序类: ItineraryCompare

  1. package week13; 
  2.  
  3. import java.util.Comparator; 
  4.  
  5. import week12.AirTicket; 
  6.  
  7. /** 
  8. * 13.9 按照 Itinerary的tostring值由低到高排序 
  9. */ 
  10. public class ItineraryCompare implements Comparator<AirTicket> 
  11. { 
  12. /** 
  13. * @return 根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。 
  14. */ 
  15. @Override 
  16. public int compare(AirTicket t1, AirTicket t2) 
  17. { 
  18. return t1.getItinerary().toString().compareTo(t2.getItinerary().toString()); 
  19. } 
  20. } 

13.10 测试类: AirTicketApp

  1. package week13; 
  2.  
  3. import java.util.Scanner; 
  4.  
  5. /** 
  6. * 13.10 测试类 
  7. */ 
  8. public class AirTicketApp 
  9. { 
  10. public static void main(String[] args) 
  11. { 
  12. // 1. 创建AirTicketProcessor对象 
  13. AirTicketProcessor atp = new AirTicketProcessor();  
  14.  
  15. // 2. 判断命令行是否有参数(args.lengh的长度是否为0), 
  16. // 如果没有,则输出“命令行中没有提供文件名,程序终止” 
  17. Scanner scan = new Scanner(System.in); 
  18.  
  19. System.out.print("请输入文件名:"); // air_ticket_data.csv 
  20. String fileName = scan.nextLine(); 
  21. scan.close(); 
  22. if (fileName.length() == 0) 
  23. { 
  24. System.out.println("命令行中没有提供文件名,程序终止"); 
  25. System.exit(0); 
  26. } 
  27.  
  28. // 3.调用 AirTicketProcessor的方法读入数据文件,输出三个报告。 
  29. atp.readAirTicketFile(fileName); 
  30. System.out.println("----------Air Ticket Report-----------"); 
  31. System.out.println(atp.generateReport()); 
  32. System.out.println("----------Air Ticket Report (by Flight Number)-----------"); 
  33. System.out.println(atp.generateReportByFlightNum()); 
  34. System.out.println("----------Air Ticket Report (by Itinerary)-----------"); 
  35. System.out.println(atp.generateReportByItinerary()); 
  36.  
  37. // 期间有如果没有找到文件,则抛出异常“文件没有找到,程序终止” 
  38. // (我已经在AirTicketProcessor中捕获异常,故这里省略了。) 
  39. // (如果按照题目意思,需要将readAirTicketFile方法中 抛出异常,在这里捕获即可。) 
  40. } 
  41. } 

运行结果:

 

enter description here

 

第二次小组作业:???

posted @ 2016-11-18 21:12  oucbl  阅读(653)  评论(0)    收藏  举报