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

一个球从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);
	}
}


你可能感兴趣的:(java修炼笔记)