跑步編程
1. JAVA編程題龜兔賽跑
class Animal {
public double speed;
public void run(int length) {
System.out.println(length/this.speed);
}
}
class Rabbit extends Animal {
Rabbit(int speed) {
super.speed = speed;
}
@Override
public void run(int length) {
System.out.println("Rabbit time = "+length/this.speed +" seconds");
}
}
class Tortoise extends Animal {
Tortoise(int speed) {
super.speed = speed;
}
@Override
public void run(int length) {
System.out.println("Tortoise time = "+length/this.speed +" seconds");
}
}
public class Match {
public static int length = 100;
private static void begin(Rabbit r,Tortoise t) {
r.run(length);
t.run(length);
}
public static void main(String[] args) {
Rabbit r = new Rabbit(20);
Tortoise t = new Tortoise(5);
begin(r,t);
}
}
2. 用C語言編程:繪制一架小車,在屏幕上來回奔跑
用flash可以嗎?C語言貌似有點難
不過我想到一種方法
你用字元繪製成小車
然後統一輸出
做一個循環
反復輸出
每次輸出
空格加1
做成++
當輸出當一定數值時
再做成--
這樣就應該能像你說的那樣來回跑了吧!
3. JAVA的程序設計,設計一個龜兔賽跑的線程類模擬參與賽跑。
感覺挺有趣的,試著寫了個~
public static void main(String[] arg) {
new wugui().run();
new tuzi().run();
}
static class wugui {
final int su = 4;// 烏龜的速度是每秒4米
public static boolean hasEnd = false;// 是否已經跑到終點
public void run() {
new Thread() {
public void run() {
int distance = 0;
while (distance < 100) {
try {
Thread.sleep(1000);
distance += su;
System.out.println("小烏龜跑了" + distance + "米");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
hasEnd = true;
if (tuzi.hasEnd) {
System.out.println("嗚嗚,差一點點就贏了~");
} else {
System.out.println("勝利是屬於有準備的人的,你的自大害了你!-------烏龜贏了");
}
}
}.start();
}
}
static class tuzi {
final int su = 5;// 兔子的速度是每秒5米
public static boolean hasEnd = false;// 是否已經跑到終點
public void run() {
new Thread() {
@Override
public void run() {
int distance = 0;// 跑了多少米
boolean hasXiuXi = false;// 是否休息過
while (distance < 100) {
try {
Thread.sleep(1000);
distance += su;
System.out.println("小兔子跑了" + distance + "米");
if (distance > 50 && !hasXiuXi) {
System.out.println("小兔子累了,決定休息一會兒~");
Thread.sleep((long) (10000 * Math.random()));
System.out.println("小兔子休息夠了,又開始跑了,決一勝負吧!");
hasXiuXi = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
hasEnd = true;
if (wugui.hasEnd) {
System.out.println("嗚嗚,早知道就不休息了~");
} else {
System.out.println("哇哈哈,你個戰5渣也想贏我~~做夢去吧!!-------兔子贏了");
}
}
}.start();
}
}