面向对象解决球的反弹问题

一个球从100米高度自由落下,每次落地后反跳回原高度的一半;

 再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?


 法1:用面向对象的方式模拟出球的运动过程来求解。

(第一版)

public class Boll {
	double heigh = 100;
	double len = 0;
	public Boll(){
	}
	public void fall(){
		len += heigh;
	}
	public void rebound(){
		heigh /= 2;
		len += heigh;
	}
	public static void main(String[] args) {
		int n = 10;
		Boll bo = new Boll();
		for (int i = 0; i < n; i++) {
			bo.fall();
			bo.rebound();
		}
		System.out.println("第"+n+"落地的总路径长度是:"+(bo.len-bo.heigh));
		System.out.println("第"+n+"次反弹的高度是:"+bo.heigh);
	}
}
(第二版)

public class Ball {
	private double height;
	private int downTimes;
	private int jumpTimes;
	private double sum;
	public Ball(double height) {
		this.height = height;
	}
	public void fall(){
		downTimes++;
		sum += height; 
	}
	
	public void jump(){
		jumpTimes++;
		height /= 2; 
		sum += height;
	}
	
	public static void main(String[] args) {
		Ball ball = new Ball(100);
		while(true){
			ball.fall();
			if(ball.downTimes==10){
				System.out.println("sum="+ball.sum);
				break;
			}
			
			ball.jump();
		}
		System.out.println("------------");
		Ball ball2 = new Ball(100);
		while(true){
			ball2.fall();
			ball2.jump();
			if(ball2.jumpTimes==10){
				System.out.println("height="+ball2.height);
				break;
			}
		}
	}
}
法2:用面向过程的方式以for循环的方式模拟出球的运行过程来求解

public class Boll {
	double heigh = 100;
	double len = 0;
	public Boll(){
	}
	public void fall(){
		len += heigh;
	}
	public void rebound(){
		heigh /= 2;
		len += heigh;
	}
	public static void main(String[] args) {
		int n = 10;
		Boll bo = new Boll();
		for (int i = 0; i < n; i++) {
			bo.fall();
			bo.rebound();
		}
		System.out.println("第"+n+"落地的总路径长度是:"+(bo.len-bo.heigh));
		System.out.println("第"+n+"次反弹的高度是:"+bo.heigh);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值