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. private String lable; //存储标签 
  11. private double radius; //圆柱半径 
  12. private double height; //圆柱的高 
  13. public Cylinder(String lable, double radius, double height) 

  14. this.lable = lable; 
  15. this.radius = radius; 
  16. this.height = height; 

  17.  
  18. public String getLable() 

  19. return lable; 

  20.  
  21. public boolean setLable(String lable) 

  22. boolean flag = true
  23.  
  24. if (lable.isEmpty()) flag = false
  25. else this.lable = lable.trim(); 
  26. //String.trim()截去字符串开头和末尾的空白 
  27. return flag; 

  28.  
  29. public double getRadius() 

  30. return radius; 

  31.  
  32. public void setRadius(double radius) 

  33. this.radius = radius; 

  34.  
  35. public double getHeight() 

  36. return height; 

  37.  
  38. public void setHeight(double height) 

  39. this.height = height; 

  40.  
  41. //返回圆柱底面直径 
  42. public double diameter() 

  43. return radius * 2

  44.  
  45. //返回圆柱底面周长 
  46. public double circumference() 

  47. return diameter() * Math.PI; 

  48.  
  49. //返回 表面积 = 圆柱底面积×2 + 底面周长×高 
  50. public double area() 

  51. return Math.PI * radius * radius * 2 
  52. + circumference() * height; 

  53.  
  54. //返回 圆柱底体积 
  55. public double volumn() 

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

  57.  
  58. @Override 
  59. public String toString() 

  60. String output = null
  61. DecimalFormat df = new DecimalFormat("#,##0.0##"); 
  62. output = lable 
  63. + " is a cylinder with radius = " + df.format(radius) 
  64. + " units and height = " + df.format(height) 
  65. + " units, " 
  66. + "\nwhich has diameter = " + df.format(diameter()) 
  67. + " units, circumference = " + df.format(circumference()) 
  68. + " units, " 
  69. + "\narea = " + df.format(area()) 
  70. + " square units, and volume = " + df.format(volumn()) 
  71. + " cubic units.\n"
  72. return output; 

  73.  
  74. public static void main(String[] args) 

  75. Cylinder c1 = new Cylinder("Small Example", 4.0, 10.0); 
  76. Cylinder c2 = new Cylinder("Medium Example", 22.1, 30.6); 
  77. Cylinder c3 = new Cylinder("Large Example", 100.0, 200.0); 
  78. c1.setLable(""); 
  79. System.out.println(c1); 
  80. System.out.println(c2); 
  81. System.out.println(c3); 


  82.  

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. private String listName; 
  11. private ArrayList<Cylinder> cList; 
  12.  
  13. CylinderList(String listName, ArrayList<Cylinder> cList) 

  14. this.listName = listName; 
  15. this.cList = cList; 

  16.  
  17. //返回一个代表几何名字的字符串 
  18. public String getName() 

  19. return listName; 

  20.  
  21. //返回代表集合中Cylinder对象的个数 
  22. public int numberOfCylinders() 

  23. return cList.size(); 

  24.  
  25. //返回 所有的Cylinder对象的 高 的和 
  26. public double totalHeight() 

  27. double totalHeight = 0
  28. for (Cylinder cylinder : cList) 

  29. totalHeight += cylinder.getHeight(); 

  30. return totalHeight; 

  31.  
  32. //返回 所有的Cylinder对象的 圆柱底面直径 的和 
  33. public double totalDiameter() 

  34. double totalDiameter = 0
  35. for (Cylinder cylinder : cList) 

  36. totalDiameter += cylinder.diameter(); 

  37. return totalDiameter; 

  38.  
  39. //返回 所有的Cylinder对象的 面积 之和 
  40. public double totalArea() 

  41. double totalArea = 0
  42. for (Cylinder cylinder : cList) 

  43. totalArea += cylinder.area(); 

  44. return totalArea; 

  45.  
  46. //返回 所有的Cylinder对象的 体积 之和 
  47. public double totalVolume() 

  48. double totalVolume = 0
  49. for (Cylinder cylinder : cList) 

  50. totalVolume += cylinder.volumn(); 

  51. return totalVolume; 

  52.  
  53. //返回 所有的Cylinder对象 面积 的 平均值 
  54. public double averageArea() 

  55. double averageArea = 0
  56. if (cList.size()>0

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

  58. return averageArea; 

  59.  
  60. //返回 所有的Cylinder对象 体积 的 平均值 
  61. public double averageVolume() 

  62. double averageVolume = 0
  63. if (cList.size()>0

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

  65. return averageVolume; 

  66.  
  67. //返回 集合的名字及集合中每一个对象的toString方法 
  68. public String toString() 

  69. String output = "\n" + listName + "\n\n"
  70. for (Cylinder cylinder : cList) 

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

  72. return output; 

  73.  
  74. //返回 集合的名字及Cylinder对象个数, 
  75. //总面积,总体积,平均面积及平均体积 
  76. public String summaryInfo() 

  77. String output = null
  78. DecimalFormat df = new DecimalFormat("#,##0.0##"); 
  79. output = "-----" + listName + " Summary-----" 
  80. + "\nNimber of Cylinders: " + numberOfCylinders() 
  81. + "\nTotal Area: " + df.format(totalArea()) 
  82. + "\nTotal Volume: " + df.format(totalVolume()) 
  83. + "\nTotal Height: " + df.format(totalHeight()) 
  84. + "\nTotal Diameter: " + df.format(totalDiameter()) 
  85. + "\nAverage Area: " + df.format(averageArea()) 
  86. + "\nAverage Volume: " + df.format(averageVolume()); 
  87. return output; 


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. public static void main(String[] args) throws FileNotFoundException 

  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.  
  29. ArrayList<Cylinder> cList = new ArrayList<>(10); 
  30. CylinderList cylinderList = null;//new CylinderList(listName, cList) 
  31.  
  32. System.out.print("Enter file name: "); 
  33. String fileName = scan0.nextLine(); // cylinder_0.dat 
  34. scan0.close(); 
  35.  
  36. File file = new File("resource/" + fileName); 
  37. if(file.exists()) 

  38. inputStream = new Scanner(file); 
  39.  
  40. String listName = inputStream.nextLine(); 
  41. while (inputStream.hasNextLine()) 

  42. String line = inputStream.nextLine(); 
  43. //使用逗号分隔line,例:Small Example, 4.0, 10.0 
  44. scan1 = new Scanner(line); 
  45. scan1.useDelimiter(","); 
  46. if (scan1.hasNext()) 

  47. lable = scan1.next(); 
  48. radius = Double.parseDouble(scan1.next()); 
  49. height = Double.parseDouble(scan1.next()); 
  50. //创建Cylinder对象并加入ArrayList<Cylinder>中 
  51. cList.add(new Cylinder(lable, radius, height)); 

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

  53. inputStream.close(); 
  54. //初始化CylinderList对象 
  55. cylinderList = new CylinderList(listName, cList); 
  56. System.out.print(cylinderList.toString()); 
  57. System.out.println(cylinderList.summaryInfo()); 

  58. else 

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



  60.  

运行结果:

 

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. private String listName = null
  16. private Scanner scan = null
  17. private Scanner inputStream = null;  
  18. private ArrayList<Cylinder> cList = null
  19.  
  20. /** 
  21. *  
  22. * @param listName 
  23. * @param cList 
  24. */ 
  25. CylinderList(String listName, ArrayList<Cylinder> cList) 

  26. this.listName = listName; 
  27. this.cList = cList; 

  28. /***************************以下为新增方法***********************************/ 
  29. /** 
  30. * 接收一个代表文件名字的字符串参数,读入文件内容将其存储到集合名字变量及 ArrayList类型的集合变量中; 
  31. * 利用集合名字及集合变量生成 CylinderList对象;最后返回该 CylinderList对象; 
  32. * @param fileName 
  33. * @return 
  34. * @throws FileNotFoundException 
  35. */ 
  36. public CylinderList readFile(String fileName) throws FileNotFoundException 

  37. CylinderList cylinderList = null
  38. String lable;  
  39. double radius;  
  40. double height; 
  41. String nameList = null
  42.  
  43. //读文件并赋值 
  44. File file = new File(fileName);  
  45. if(file.exists())  
  46. {  
  47. inputStream = new Scanner(file);  
  48.  
  49. nameList = inputStream.nextLine();  
  50. while (inputStream.hasNextLine())  
  51. {  
  52. String line = inputStream.nextLine();  
  53. //使用逗号分隔line,例:Small Example, 4.0, 10.0  
  54. scan = new Scanner(line);  
  55. scan.useDelimiter(",");  
  56. if (scan.hasNext())  
  57. {  
  58. lable = scan.next();  
  59. radius = Double.parseDouble(scan.next());  
  60. height = Double.parseDouble(scan.next());  
  61. //创建Cylinder对象并加入ArrayList<Cylinder>中  
  62. cList.add(new Cylinder(lable, radius, height));  


  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. cList.add(new Cylinder(label, radius, height)); 

  80.  
  81. /** 
  82. * 接收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象,则返回该对象并删除之; 
  83. * 否则返回 null; 
  84. * @param label 
  85. * @return 
  86. */ 
  87. public Cylinder deleteCylinder(String label) 

  88. Cylinder cylinder = null
  89. for (int i = 0; i < cList.size(); i++) 

  90. //如果找到 先赋值 后 删除 
  91. if (cList.get(i).getLable().equalsIgnoreCase(label) == true

  92. cylinder = cList.get(i); 
  93. cList.remove(i); 


  94. return cylinder; 

  95.  
  96. /** 
  97. * 参数接收收一个代表 Cylinder的 label值的字符串,如果在 CylinderList对象中找到了该对象, 
  98. * 则返回该对象;否则返回 null; 
  99. * @param label 
  100. * @return 
  101. */ 
  102. public Cylinder findCylinder(String label) 

  103. Cylinder cylinder = null
  104. for (int i = 0; i < cList.size(); i++) 

  105. //如果找到 赋值 
  106. if (cList.get(i).getLable().equalsIgnoreCase(label) == true

  107. cylinder = cList.get(i); 


  108. return cylinder; 

  109. /** 
  110. * String类中两个方法的比较: 
  111. * equals:将此字符串与指定的对象比较。当且仅当该参数不为 null, 
  112. * 并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。  
  113. * equalsIgnoreCase:将此 String 与另一个 String 比较,不考虑大小写。如果两个字符串的长度相同, 
  114. * 并且其中的相应字符都相等(忽略大小写),则认为这两个字符串是相等的。  
  115. */ 
  116. /***************************以上为新增方法*********************************/ 
  117.  
  118. .... 

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. private static void showMenu() 

  29. //输出带有描述的 7个选项信息 
  30. System.out.println("Cylinder List System Menu"); 
  31. System.out.println("R - ReadFile and Create Cylinder List"); 
  32. System.out.println("P - Print Cylinder List"); 
  33. System.out.println("S - Print Summary"); 
  34. System.out.println("A - Add Cylinder"); 
  35. System.out.println("D - Delete Cylinder"); 
  36. System.out.println("F - Find Cylinder"); 
  37. System.out.println("Q - Quit"); 

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

  40. //创建一个 Cylinder集合 
  41. ArrayList<Cylinder> clist = new ArrayList<>(); 
  42.  
  43. String sName = "***no list name assigned***"
  44. CylinderList cylinderList = new CylinderList(sName, clist); 
  45.  
  46.  
  47. Scanner scan = new Scanner(System.in); 
  48. char key; //输入的key值 
  49.  
  50. showMenu(); //显示提示菜单 
  51. while (true

  52. //提示用户进行选择 
  53. System.out.print("\nEnter Code [R, P, S, A, D, F or Q]: "); 
  54.  
  55. key = scan.nextLine().charAt(0); 
  56. switch (key) 

  57. case 'r'://resource/cylinder_1.dat 
  58. case 'R'://ReadFile and Create Cylinder List 
  59. System.out.print("\tFile name: "); 
  60. //读文件转化为CylinderList对象后重新赋值 
  61. cylinderList = cylinderList.readFile(scan.nextLine()); 
  62. System.out.println("\tFile read in and Cylinder List created"); 
  63. break
  64. case 'p'
  65. case 'P'://Print Cylinder List 
  66. System.out.println(cylinderList); 
  67. break
  68. case 's'
  69. case 'S'://Print Summary 
  70. System.out.println(cylinderList.summaryInfo()); 
  71. break
  72. case 'a'
  73. case 'A'://Add Cylinder 
  74. System.out.print("\tLabel: "); 
  75. String labelA = scan.nextLine(); 
  76. System.out.print("\tRadius: "); 
  77. double radius = Double.parseDouble(scan.nextLine()); 
  78. System.out.print("\tHeight: "); 
  79. double height =Double.parseDouble(scan.nextLine()); 
  80. cylinderList.addCylinder(labelA, radius, height); 
  81. System.out.println("\t*** Cylinder added ***"); 
  82. break
  83. case 'd'
  84. case 'D'://Delete Cylinder 
  85. System.out.print("\tLabel: "); 
  86. String labelD = scan.nextLine(); 
  87. if(cylinderList.deleteCylinder(labelD) == null
  88. System.out.println("\t\"" + labelD + "\" not found"); 
  89. else 
  90. System.out.println("\t\"" + labelD +"\" deleted"); 
  91. break
  92. case 'f'
  93. case 'F'://Find Cylinder 
  94. System.out.print("\tLabel: "); 
  95. String labelF = scan.nextLine(); 
  96. if(cylinderList.findCylinder(labelF) == null
  97. System.out.println("\t\"" + labelF + "\" not found"); 
  98. else 
  99. System.out.println(cylinderList.findCylinder(labelF)); 
  100. break
  101. case 'q'
  102. case 'Q'://Quit 
  103. return
  104. default
  105. System.out.println("\t*** invalid code ***"); 




运行演示:

 

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. protected String name; 
  9. protected double price; 
  10. private static double taxRate = 0
  11.  
  12. public static void main(String[] args) 

  13. InventoryItem.setTaxRate(0.08); 
  14. InventoryItem item1 = new InventoryItem("Birdseed", 7.99); 
  15. InventoryItem item2 = new InventoryItem("Picture", 10.99); 
  16.  
  17. System.out.println(item1); 
  18. System.out.println(item2); 

  19.  
  20. /** 
  21. * 初始化 
  22. * @param name 
  23. * @param price 
  24. */ 
  25. public InventoryItem(String name, double price) 

  26. this.name = name; 
  27. this.price = price; 

  28.  
  29. @Override 
  30. public String toString() 

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

  32.  
  33. /** 
  34. * 货物含税的价格 
  35. * @return 
  36. */ 
  37. public double calculateCost() 

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

  39.  
  40. public String getName() 

  41. return name; 

  42.  
  43. /** 
  44. * 设置税率; 
  45. * 静态方法不能使用隐含(或明确的把this作为其调用对象) 的实例变量(或非静态方法) 
  46. * @param taxRateIn 
  47. */ 
  48. public static void setTaxRate(double taxRateIn) 

  49. taxRate = taxRateIn; 


运行结果:
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. protected double weight; //电子货物重量 
  9. public static final double SHIPPING_COST = 1.5;//每磅的货运费用 
  10.  
  11. public ElectronicsItem(String name, double price, double weight) 

  12. super(name, price); 
  13. this.weight = weight; 

  14.  
  15. @Override 
  16. public double calculateCost() 

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

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

  20. InventoryItem.setTaxRate(0.08); 
  21. ElectronicsItem eItem = new ElectronicsItem("Monitor", 100, 10.0); 
  22. System.out.println(eItem); 


  23.  

运行结果:
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. public OnlineTextItem(String name, double price) 

  12. super(name, price); 
  13. // TODO Auto-generated constructor stub 

  14.  
  15. @Override 
  16. public double calculateCost() 

  17. return price; 

  18.  

  19.  

10.4 OnlineArticle.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.4 OnlineArticle.java 
  5. * 电子类文本物品:OnlineTextItem的派生类 
  6. */ 
  7. public class OnlineArticle extends OnlineTextItem 

  8. private int wordCount; //记录字数 
  9.  
  10. public OnlineArticle(String name, double price) 

  11. super(name, price); 
  12. this.wordCount = 0

  13.  
  14. @Override 
  15. public String toString() 

  16. return name + ": $"+ price  
  17. + " " + this.wordCount;  

  18.  
  19. public void setWordCount(int wordCount) 

  20. this.wordCount = wordCount; 

  21.  

  22.  

10.5 OnlineBook.java

  1. package week10; 
  2.  
  3. /** 
  4. * 10.5 OnlineBook.java 
  5. * 电子书:OnlineTextItem的派生类 
  6. */ 
  7. public class OnlineBook extends OnlineTextItem 

  8. protected String author; //电子书作者 
  9.  
  10. public OnlineBook(String name, double price) 

  11. super(name, price); 
  12. author = "Author Not Listed"

  13.  
  14. public void setAuthor(String author) 

  15. this.author = author; 

  16.  
  17. @Override 
  18. public String toString() 

  19. return name + " - " 
  20. + author +": $" + price; 

  21.  
  22. public static void main(String[] args) 

  23. OnlineBook book = new OnlineBook("A Novel Novel", 9.99); 
  24. System.out.println(book); 
  25.  
  26. book.setAuthor("Jane Lane"); 
  27. System.out.println(book); 

  28.  

  29.  

运行结果:
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. public static void main(String[] args) 

  11. InventoryItem.setTaxRate(0.05); 
  12.  
  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.  
  18. item3.setWordCount(700); 
  19. item4.setAuthor("Kathy&Bert"); 
  20.  
  21. System.out.println(item1); 
  22. System.out.println(item2); 
  23. System.out.println(item3); 
  24. System.out.println(item4); 
  25.  
  26. System.out.println("All inventory:\n\n" + myItems); 
  27. System.out.println("Total: " + myItems.calculateTotal(2)); 


  28.  

运行结果:
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. private InventoryItem[] inventory; 
  12. private int count; 
  13.  
  14. public ItemsList() 

  15. inventory = new InventoryItem[20]; 
  16. count = 0

  17.  
  18. /** 
  19. * 增加一个item 
  20. * @param itemIn 
  21. */ 
  22. public void addItem(InventoryItem itemIn) 

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

  24.  
  25. /** 
  26. * 返回代表数组各元素价格的总和 
  27. * @param electronicsSurcharge,代表征收ElectronicsItem的附加费 
  28. * @return 
  29. */ 
  30. public double calculateTotal(double electronicsSurcharge) 

  31. double totalCost = 0
  32.  
  33. /** 需要遍历 inventory数组的每一个元素,将价格 (cost)累加到和上。 
  34. * 如果元素为 ElectronicsItem类的引用变量 ,则激活calculateCost方法, 
  35. * 增加该的 方法的electronicsSurcharge 
  36. */ 
  37. for (int i = 0; i < count; i++) 

  38. if (inventory[i] instanceof ElectronicsItem) 

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

  40. else 

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

  42.  

  43. return totalCost; 

  44.  
  45. @Override 
  46. public String toString() 

  47. String output = ""
  48. for (int i = 0; i < count; i++) 

  49. output += inventory[i].toString(); 
  50. output += "\n"

  51. return output; 


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. public static void main(String[] args) 

  13. // a)初始化名为myItems的ItemsList对象 
  14. ItemsList myItems = new ItemsList(); 
  15.  
  16. // b)通过InventoryItem的setTaxRate方法设置税率为 0.05 
  17. InventoryItem.setTaxRate(0.05); 
  18.  
  19. // c)初始化以下4个货物并将其增加到myItems中 
  20. ElectronicsItem electItem = new ElectronicsItem("笔记本", 1234.56, 10); 
  21. InventoryItem item = new InventoryItem("机油", 9.8); 
  22. OnlineBook book = new OnlineBook("疯狂Java讲义", 12.3); 
  23. book.setAuthor("李刚"); 
  24. OnlineArticle article = new OnlineArticle("如何学好Java", 3.4); 
  25. article.setWordCount(700); 
  26.  
  27. myItems.addItem(electItem); 
  28. myItems.addItem(item); 
  29. myItems.addItem(book); 
  30. myItems.addItem(article); 
  31.  
  32. System.out.println("All inventory:\n\n" + myItems); 
  33.  
  34. System.out.println("Total: " + myItems.calculateTotal(1.215)); 

  35.  

运行结果:
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. private String formAirport; 
  8. private String toAirport; 
  9. private String depDateTime; 
  10. private String arrDateTime; 
  11. private int miles; 
  12.  
  13. public Itinerary 
  14. (String formAirport,String toAirport,String depDateTime,String arrDateTime,int miles) 

  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. return depDateTime; 

  23.  
  24. public String getArrDateTime() 

  25. return arrDateTime; 

  26.  
  27. public int getMiles() 

  28. return miles; 

  29.  
  30. @Override 
  31. public String toString() 

  32. String output = "" 
  33. + "" + formAirport 
  34. + "-" + toAirport 
  35. + " (" + depDateTime 
  36. + " - " + arrDateTime 
  37. + ")" 
  38. + " " + miles; 
  39. return output; 


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. private String flightNum; //航班号 
  11. private Itinerary itinerary; //行程 
  12. private double baseFare; //飞机票基本费用 
  13. private double fareAdjustmentFactor; //费用调整因素 
  14.  
  15. public AirTicket(String flightNum,Itinerary itinerary,double baseFare,double fareAdjustmentFactor) 

  16. this.flightNum = flightNum; 
  17. this.itinerary = itinerary; 
  18. this.baseFare = baseFare; 
  19. this.fareAdjustmentFactor = fareAdjustmentFactor; 

  20.  
  21. public String getFlightNum() 

  22. return flightNum; 

  23.  
  24. public Itinerary getItinerary() 

  25. return itinerary; 

  26.  
  27. public double getBaseFare() 

  28. return baseFare; 

  29.  
  30. public double getFareAdjustmentFactor() 

  31. return fareAdjustmentFactor; 

  32.  
  33. /** 
  34. * 自然比较方法:(忽略大小写)比较航班号 
  35. * @return 该对象小于、等于或大于指定对象 at,分别返回负整数、零或正整数。  
  36. */ 
  37. @Override 
  38. public int compareTo(AirTicket at) 

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

  40.  
  41. @Override 
  42. public String toString() 

  43. Format formater = new DecimalFormat("###,###.00"); 
  44. String output = "" 
  45. + "\nFlight: " + flightNum 
  46. + "\n" + itinerary 
  47. + " (" + totalAwardMiles() + " award miles)" 
  48. + "\nBase Fare: $" + formater.format(baseFare) 
  49. + " Fare Adjustment Factor: " + fareAdjustmentFactor 
  50. + "\nTotal Fare: $" + formater.format(totalFare()) 
  51. + "\t"
  52. return output; 

  53.  
  54. public abstract double totalFare()
  55.  
  56. public abstract double totalAwardMiles()
  57.  

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.3 飞机票子类---经济舱机票 
  5. */ 
  6. public class Economy extends AirTicket 

  7. private final static double AWARDMILESFACTOR = 1.5
  8.  
  9. public Economy(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor) 

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

  11.  
  12. @Override 
  13. public double totalFare() 

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

  15.  
  16. @Override 
  17. public double totalAwardMiles() 

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

  19.  
  20. @Override 
  21. public String toString() 

  22. return super.toString() + " (class Economy)\n " 
  23. + "Includes Award Miles Factor: " 
  24. + AWARDMILESFACTOR; 


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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.4 飞机票子类---商务舱机票 
  5. */ 
  6. public class Business extends AirTicket 

  7. private final static double AWARDMILESFACTOR = 2; //这里我改为2(题目为1.5) 
  8. private double foodAndBeverages; 
  9. private double entertaiment; 
  10.  
  11. public Business(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  12. double foodAndBeverages, double entertaiment) 

  13. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 
  14. this.foodAndBeverages = foodAndBeverages; 
  15. this.entertaiment = entertaiment; 

  16.  
  17. @Override 
  18. public double totalFare() 

  19. return super.getBaseFare() * super.getFareAdjustmentFactor() 
  20. + foodAndBeverages + entertaiment; 

  21.  
  22. @Override 
  23. public double totalAwardMiles() 

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

  25.  
  26. @Override 
  27. public String toString() 

  28. return super.toString()+ " (class Business)\n " 
  29. + "Includes Food/Beverage: $" + foodAndBeverages 
  30. + " Entertaiment: $" + entertaiment; 

  31.  

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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.5 飞机票子类---不可退的机票 
  5. */ 
  6. public class NonRefundable extends AirTicket 

  7. private double discountFactor; 
  8.  
  9. public NonRefundable(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  10. double discountFactor) 

  11. super(flightNum, itinerary, baseFare, fareAdjustmentFactor); 
  12. this.discountFactor = discountFactor; 

  13. @Override 
  14. public double totalFare() 

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

  17.  
  18. @Override 
  19. public double totalAwardMiles() 

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

  21.  
  22. @Override 
  23. public String toString() 

  24. return super.toString()+ " (class NonRefundable)\n " 
  25. + "Includes DiscountFactor: " 
  26. + discountFactor; 


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

  1. package week12; 
  2.  
  3. /** 
  4. * 12.6 飞机票子类---商务舱机票子类---精英类机票 
  5. */ 
  6. public class Elite extends Business 

  7. private double cService; 
  8.  
  9. public Elite(String flightNum, Itinerary itinerary, double baseFare, double fareAdjustmentFactor, 
  10. double foodAndBeverages, double entertaiment, double cService) 

  11. super(flightNum, itinerary, baseFare, fareAdjustmentFactor, foodAndBeverages, entertaiment); 
  12. this.cService = cService; 

  13.  
  14. @Override 
  15. public double totalFare() 

  16. return super.totalFare() + cService; 

  17.  
  18. @Override 
  19. public double totalAwardMiles() 

  20. return super.totalAwardMiles(); 

  21.  
  22. @Override 
  23. public String toString() 

  24. return super.toString()+ " \n " 
  25. + "Includes: Comm Services: $" + cService; 


12.7 测试类: AirTicketProcessor

  1. package week12; 
  2.  
  3. import java.util.Arrays; 
  4.  
  5. /** 
  6. * 12.7 测试类 
  7. */ 
  8. public class AirTicketProcessor 

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

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


运行结果:

 

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. private AirTicket[] Tickets; 
  21. private String[] invalidRecords; 
  22.  
  23. public AirTicketProcessor() 

  24. Tickets = new AirTicket[0]; 
  25. invalidRecords = new String[0]; 

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

  31. // 这里我设置为 工程 目录的 resource 下 
  32. String path = "resource/" + fileName; 
  33. File file = new File(path); 
  34.  
  35. BufferedReader reader = null
  36. try 

  37. reader = new BufferedReader(new FileReader(file)); 
  38. String tempString = null; // 每行的字符串临时变量 
  39. // 一次读入一行,直到读入null为文件结束 
  40. while ((tempString = reader.readLine()) != null

  41. try 

  42. String[] lineArr = tempString.split(","); 
  43. // 以 逗号 为分隔符, 并添加 票据信息 
  44. switch (lineArr[0]) 

  45. case "N"
  46. addAirTicket(new NonRefundable(lineArr[1], 
  47. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  48. Integer.parseInt(lineArr[6])), 
  49. Integer.parseInt(lineArr[7]), Double.parseDouble(lineArr[8]), 
  50. Double.parseDouble(lineArr[9]))); 
  51. break
  52. case "E"
  53. addAirTicket(new Economy(lineArr[1], 
  54. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  55. Integer.parseInt(lineArr[6])), 
  56. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]))); 
  57. break
  58. case "B"
  59. addAirTicket(new Business(lineArr[1], 
  60. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  61. Integer.parseInt(lineArr[6])), 
  62. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 
  63. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]))); 
  64. break
  65. case "F"
  66. addAirTicket(new Elite(lineArr[1], 
  67. new Itinerary(lineArr[2], lineArr[3], lineArr[4], lineArr[5], 
  68. Integer.parseInt(lineArr[6])), 
  69. Double.parseDouble(lineArr[7]), Double.parseDouble(lineArr[8]), 
  70. Double.parseDouble(lineArr[9]), Double.parseDouble(lineArr[10]), 
  71. Double.parseDouble(lineArr[11]))); 
  72. break
  73. default
  74. addInvaildRecord(tempString); 
  75. break

  76. } catch (Exception e) 

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


  78. } catch (IOException e) 

  79. System.out.println("Not find AirTicketFile!"); 
  80. // e.printStackTrace(); 
  81. } finally 

  82. if (reader != null

  83. try 

  84. reader.close(); 
  85. } catch (IOException e1) 





  86.  
  87. /** 
  88. * 将AirTicket类数组的长度增加1,之后将传入的对象放入数组中 
  89. *  
  90. * @param airTicket 
  91. */ 
  92. public void addAirTicket(AirTicket airTicket) 

  93. Tickets = Arrays.copyOf(Tickets, Tickets.length + 1); 
  94. Tickets[Tickets.length - 1] = (airTicket); 

  95.  
  96. /** 
  97. * 将invalidRecords数组的长度增加1,将传入的字符串放入数组中(每一行以代表机票种类的 字符开头(N, E, B和F是合法的机票种类), 
  98. * 如果开头字母不在此范围中,则此行为不合法记录) 
  99. *  
  100. * @param lineStr 
  101. */ 
  102. public void addInvaildRecord(String lineStr) 

  103. invalidRecords = Arrays.copyOf(invalidRecords, invalidRecords.length + 1); 
  104. invalidRecords[invalidRecords.length - 1] = (lineStr); 

  105.  
  106. /** 
  107. * 返回 AirTickets报告 
  108. */ 
  109. public String generateReport() 

  110. String output = ""
  111. for (AirTicket airTicket : Tickets) 

  112. output += airTicket + "\n"

  113. return output; 

  114.  
  115. /** 
  116. * 以航班号的升序 返回AirTickets报告 
  117. */ 
  118. public String generateReportByFlightNum() 

  119. String output = ""
  120.  
  121. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 
  122. Arrays.sort(orderT); 
  123.  
  124. for (AirTicket airTicket : orderT) 

  125. output += airTicket + "\n"

  126. return output; 

  127.  
  128. /** 
  129. * 以行程的升序 返回AirTickets报告 
  130. */ 
  131. public String generateReportByItinerary() 

  132. String output = ""
  133.  
  134. AirTicket[] orderT = Arrays.copyOf(Tickets, Tickets.length); 
  135. Arrays.sort(orderT, new ItineraryCompare()); 
  136.  
  137. for (AirTicket airTicket : orderT) 

  138. output += airTicket + "\n"

  139. return output; 


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. * @return 根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。 
  13. */ 
  14. @Override 
  15. public int compare(AirTicket t1, AirTicket t2) 

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


13.10 测试类: AirTicketApp

  1. package week13; 
  2.  
  3. import java.util.Scanner; 
  4.  
  5. /** 
  6. * 13.10 测试类 
  7. */ 
  8. public class AirTicketApp 

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

  10. // 1. 创建AirTicketProcessor对象 
  11. AirTicketProcessor atp = new AirTicketProcessor();  
  12.  
  13. // 2. 判断命令行是否有参数(args.lengh的长度是否为0), 
  14. // 如果没有,则输出“命令行中没有提供文件名,程序终止” 
  15. Scanner scan = new Scanner(System.in); 
  16.  
  17. System.out.print("请输入文件名:"); // air_ticket_data.csv 
  18. String fileName = scan.nextLine(); 
  19. scan.close(); 
  20. if (fileName.length() == 0

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

  23.  
  24. // 3.调用 AirTicketProcessor的方法读入数据文件,输出三个报告。 
  25. atp.readAirTicketFile(fileName); 
  26. System.out.println("----------Air Ticket Report-----------"); 
  27. System.out.println(atp.generateReport()); 
  28. System.out.println("----------Air Ticket Report (by Flight Number)-----------"); 
  29. System.out.println(atp.generateReportByFlightNum()); 
  30. System.out.println("----------Air Ticket Report (by Itinerary)-----------"); 
  31. System.out.println(atp.generateReportByItinerary()); 
  32.  
  33. // 期间有如果没有找到文件,则抛出异常“文件没有找到,程序终止” 
  34. // (我已经在AirTicketProcessor中捕获异常,故这里省略了。) 
  35. // (如果按照题目意思,需要将readAirTicketFile方法中 抛出异常,在这里捕获即可。) 


运行结果:

 

enter description here

 

第二次小组作业:???

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