初入JAVA圈,正在蹒跚前行,共勉之!
今日在论坛看到一篇写立方体的帖子,正好初学Java,小试身手,检测下学习成果。
import java.util.Scanner;
public class Cube {
public static void main(String[] ages){
// 定义变量
double l = 0;
double w = 0;
double h = 0;
Scanner scan = new Scanner(System.in);
// 接收输入参数
System.out.println("Input the cube`length : ");
if (scan.hasNextDouble()) {
l = scan.nextDouble();
}
System.out.println("Input the cube`width : ");
if (scan.hasNextDouble()) {
w = scan.nextDouble();
}
System.out.println("Input the cube`height : ");
if (scan.hasNextDouble()) {
h = scan.nextDouble();
}
// 检验数据合法性,创建对象并输出结果
if ((l > 0) && (w > 0) && (h > 0)) {
Cube cube = new Cube(l, w, h);
System.out.println("The cubes volume is : " + cube.getVolume());
} else {
System.out.println("Input property error!");
}
}
public Cube(Double length, Double width, Double height) {
this.length = length;
this.width = width;
this.height = height;
}
private Double getVolume() {
return this.length * this.width * this.height;
}
private Double length;
private Double width;
private Double height;
public Double getLength() {
return length;
}
public void setLength(Double length) {
this.length = length;
}
public Double getWidth() {
return width;
}
public void setWidth(Double width) {
this.width = width;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
}
以上。