【练习题1】
- 猜数字游戏:一个类A有一个成员变量v,有一个初值100。
- 定义一个类,对A类的成员变量v进行猜。
- 如果大了则提示大了,小了则提示小了。等于则提示猜测成功。
//A类
package zlb.day06.Practice;
public class A {
private int v=100;
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
}
//B类
package zlb.day06.Practice;
import java.util.Scanner;
public class B {
public static void main(String[] args) {
idea();
}
public static void idea() {
Scanner scanner = new Scanner(System.in);
A a = new A();
for (int j= 0; j<100; j++) {
if (j ==3) {
System.out.println("三次机会已用完,游戏失败,结束");
break;
}
System.out.println("请输入你猜测的数字:");
int i = scanner.nextInt();
if (i < a.getV()) {
System.out.println("输入的数小了");
} else if (i> a.getV()) {
System.out.println("输入的数大了");
}
if(i==a.getV()) {
System.out.println("猜测成功");
break;
}
}
}
}
练习题【2】:
- 1.创建一个Rectangle类,添加两个属性width、height。
- 2.在Rectangle中添加两个方法计算矩形的周长和面积。
- 3.编程利用Rectangle输出一个矩形的周长和面积。
package zlb.day06.Practice;
public class Rectangle {
private double height;
private double width;
public Rectangle() {
super();
}
public Rectangle(double height, double width) {
this.height = height;
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
//计算面积
public double getArea(){
double A=height*width;
return A;
}
//计算周长
public double getCir(){
double C=height*2+width*2;
return C;
}
public static void main(String[] args) {
Rectangle rectangle=new Rectangle(20.0,30.0);
System.out.println("矩形的面积是"+rectangle.getArea());
System.out.println("矩形的周长是"+rectangle.getCir());
}
}
练习题【3】:
- 请定义一个交通工具,其中有:
- 属性:速度 (Vehicle)的类,其中有: (speed),体积(size)等等
- 方法:移动(move()),设置速度(setSpeed(int speed)),加速 speedUp(),减速
- speedDown()等等. 最后在测试类 Vehicle 中的 main()中实例化一个交通工具对象,并通过方法给它
- 初始化 speed,size 的值,并且通过打印出来。另外,调用加速,减速的方法对速
度进行改变。
package zlb.day06.Practice;
public class Vehicle {
private double speed;
private int size;
public void move(){
System.out.println("交通工具可以移动");
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
if(speed>0)
{
System.out.println("当前速度为:"+speed);
}
}
public void SpeedUp(){
//加速度g
int g=40;
System.out.println("正在加速");
for (int i = 1; i < 10; i++) {
if(speed<200){
setSpeed(speed+g);
}
else if(speed>=200){
System.out.println("超速,请减速!");
break;
}
}
}
public void SpeedDown(){
//加速度g
int g=40;
System.out.println("正在减速");
for (int i = 0; i < 10; i++) {
if(speed>0) {
setSpeed(speed - g);
}
else if (speed<=0){
System.out.println("已停止移动");
break;
}
}
}
public static void main(String[] args) {
Vehicle vehicle=new Vehicle();
vehicle.move();
vehicle.size=100000;
System.out.println("它的体重为"+vehicle.size+"千克");
vehicle.setSpeed(100.00);
vehicle.SpeedUp();
vehicle.SpeedDown();
}
}