java一百个经典代码 java一百个经典代码大全

求一Java代码,要简单的 。大概一百多行的的 。题目:一球从100米高度自由落下 , 每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?
这个题目,下面我会贴出来两种代码 。其实这个题目,我烦了简单计算,想搞得有趣味性一点,结果耽误了好几天时间,最后发现搞的也不好 。
先第一种,为了解题而解题 。
==== Main.java ====
public class Main {
private double TotalHeight = 100;
private double CurHeight = 50;
public void drop(int times) {
if ((times - 1) == 0) {
return;
}
setTotalHeight(getTotalHeight() + 2 * getCurHeight());
setCurHeight(getCurHeight() / 2);
drop(times - 1);
}
public double getTotalHeight() {
return TotalHeight;
}
public void setTotalHeight(double totalHeight) {
TotalHeight = totalHeight;
}
public double getCurHeight() {
return CurHeight;
}
public void setCurHeight(double curHeight) {
CurHeight = curHeight;
}
public static void main(String[] args) {
Main main = new Main();
main.drop(2);
System.out.println("Total height is " +
main.getTotalHeight());
System.out.println("Current height is " +
main.getCurHeight());
}
}
==== 然后是第二种 =====
==== Main.java ====
package main;
import javax.swing.JFrame;
import panel.BallPanel;
import time.Delay;
public class MainFrame extends JFrame {
public MainFrame(String title) {
super(title);
}
public static void main(String[] args) {
Delay delay = new Delay();
MainFrame frame = new MainFrame("Hello JFrame");
BallPanel ballPanel = new BallPanel();
frame.add(ballPanel);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
delay.initDelay();
ballPanel.setDelay(delay.getDelay());
ballPanel.loopDrop(0);
}
}
==== Delay.java ====
package time;
public class Delay {
public void initDelay() {
int g = 10;
int i = 0;
double s, t, t0 = 0.0;
delay = new int[100];
for (s = 100; s10100; s += 100) {
t = Math.sqrt(2 * s / g);
delay[i++] = (int) ((t - t0) * 100);
t0 = t;
}
}
public int[] getDelay() {
return delay;
}
private int delay[];
}
==== BallPanel.java ====
package panel;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class BallPanel extends JPanel {
public BallPanel() {
super();
}
public void paint(Graphics g) {
g.clearRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.BLUE);
g.fillOval(250, ballCenter, 30, 30);
}
public void loopDrop(int height) {
int i;
if (this.height == height) { // At bottom
for (i = 0; itargetHeight; i += MUL) {
ballCenter = this.height - i;
this.repaint();
try {
Thread.sleep(delay[(targetHeight - i - 1) / MUL]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
loopDrop(this.height - i);
} else { // At top
for (i = height; ithis.height; i += MUL) {
ballCenter = i;
this.repaint();
try {
Thread.sleep(delay[(i - height) / MUL]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
targetHeightV = targetHeightV / 2;
targetHeight = targetHeightV;
if (targetHeight != 0) {
loopDrop(i);
}
}
}
public void setDelay(int delay[]) {
this.delay = delay;
}
private int extracted() {
return 100 * MUL;
}
private int targetHeight = extracted();

推荐阅读