【练习题】01.类的成员变量:
设计一个立方体类Box,定义三个属性,分别是长,宽,高。定义二个方法,分别计算并输出立方体的体积和表面积
//设计一个立方体类Box,定义三个属性,分别是长,宽,高。定义二个方法,分别计算并输出立方体的体积和表面积
package cn.edu.nefu1;
import java.util.Scanner;
public class Box {
double length;
double width;
double height;
//求体积
double volume(double length,double width,double height){
return length*width*height;
}
//求表面积
double area(double length,double width,double height){
return 2*(length*width+length*height+width*height);
}
public static void main(String[] args) {
Box box = new Box(); //实例化一个对象
System.out.println("请输入该立方体的长、宽、高:");
Scanner sc = new Scanner(System.in);
box.length = sc.nextDouble();
box.width = sc.nextDouble();
box.height = sc.nextDouble();
System.out.println("立方体的体积为:"+box.volume(box.length,box.width,box.height)); //调用方法
System.out.println("立方体的表面积为:"+box.area(box.length,box.width,box.height));
}
}
【练习题】02.类的成员变量:
请定义一个交通工具(Vehicle)的类,其中有:
属性:速度(speed),距离(distance)等等
方法:移动(move(int s)),设置速度(setSpeed(int speed)),加速speedUp(),减速speedDown()等等.
最后在测试类Vehicle中的main()中实例化一个交通工具对象,并通过方法给它初始化speed, distance的值,并且通过打印出来。另外,调用加速,减速的方法对速度进行改变。调用 move方法改变distance,并输出已经移动的距离
//请定义一个交通工具(Vehicle)的类,其中有:
// 属性:速度(speed),距离(distance)等等
// 方法:移动(move(int s)),设置速度(setSpeed(int speed)),加速speedUp(),减速speedDown()等等.
// 最后在测试类Vehicle中的main()中实例化一个交通工具对象,并通过方法给它初始化speed, distance的值,
// 并且通过打印出来。另外,调用加速,减速的方法对速度进行改变。调用 move方法改变distance,并输出已经移动的距离
package cn.edu.nefu1;
public class Vehicle {
int