OOP h04
根据所给的 Test,补充实现三个类。
0x00 Apple
根据所给信息,知道 Apple 类具有无参构造方法 Apple() 和含参构造方法 Apple(size, color),具有 getColor() 和 getSize() 方法,具有 color 和 size 属性,默认 color 为 red。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | package com.huawei.classroom.student.h04;
 
 
 
 public class Apple {
 private String color;
 private int size;
 
 public Apple() {
 this.color = "red";
 this.size = 0;
 }
 public Apple(int size, String color) {
 this.color = color;
 if (size >= 0)
 this.size = size;
 else
 this.size = 0;
 }
 
 public String getColor() {
 return this.color;
 }
 public int getSize() {
 return this.size;
 }
 }
 
 | 
0x01 Triangle
根据所给信息,需要实现设置三角形的三条边,并求其面积。
已知三角形三边求面积,利用海伦公式:
设三角形三边为 a、b 和 c,,则面积
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 
 | package com.huawei.classroom.student.h04;
 
 
 
 public class Triangle {
 private double lenA, lenB, lenC;
 
 public void setA(double len) {
 this.lenA = len;
 }
 public void setB(double len) {
 this.lenB = len;
 }
 public void setC(double len) {
 this.lenC = len;
 }
 public double getArea() {
 double p = (lenA + lenB + lenC) / 2.0;
 return Math.sqrt(p * (p-lenA) * (p-lenB) * (p-lenC));
 }
 }
 
 | 
0x02 MyStack
使用顺序栈实现。
定义最大元素数量、栈数组、数组索引作为栈顶指针,入栈和出栈对应元素的插入和索引的移动。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 
 | package com.huawei.classroom.student.h04;
 
 
 
 public class MyStack {
 private int maxSize;
 private int[] stack;
 private int top;
 
 public MyStack(int size) {
 this.maxSize = size;
 this.stack = new int[this.maxSize];
 this.top = -1;
 }
 public int pop() {
 if (this.top == -1)
 return 0;
 else
 return this.stack[top--];
 }
 public void push(int e) {
 this.stack[++top] = e;
 }
 public boolean isEmpty() {
 return top == -1;
 }
 public boolean isFull() {
 return top == this.maxSize - 1;
 }
 }
 
 |