123_面向对象练习(练习4)中的22题
原题:
- class Circle
- {
- private static double PI = 3.14;
- private double radius;
- public Circle(double r)
- {
- radius = r;
- }
- public static double compare(Circle cir[])
- {
- //补全代码,实现compare功能
-
- }
- public static void main(String args[])
- {
- Circle cir[] = new Circle[3];
- cir[0] = new Circle(1.0);
- cir[1] = new Circle(2.0);
- cir[3] = new Circle(4.0);
- System.out.println(Circle.compare(cir));
-
- }
- }
复制代码 老师给出的答案个人感觉有点小问题:(没有判断传入的对象是否为空)
- class Circle
- {
- private static double PI = 3.14;
- private double radius;
- public Circle(double r)
- {
- radius = r;
- }
- public static double compare(Circle cir[])
- {
- int max = 0;
- for(int x = 0; x< cir.length;x++)
- {
- if(cir[x]!=null && cir[max]!=null) //先判断都不为空对象...
- {
- if(cir[x].radius>cir[max].radius)
- max = x;
- }else if(cir[max]==null)
- {
- max++;
- }
-
- }
- return cir[max].radius
- }
- public static void main(String args[])
- {
- Circle cir[] = new Circle[3];
- cir[0] = new Circle(1.0);
- cir[1] = new Circle(2.0);
- cir[3] = new Circle(4.0);
- System.out.println(Circle.compare(cir));
-
- }
- }
复制代码
|
|