public class Race {
public static void main(String[] args) {
int maxSpeed = Car.getMaxSpeedForAll();
int raceLength = 1000;
Car mario = new Car(30, "Mario");
Car luigi = new Car(30, "Luigi");
while(mario.getLocation() < raceLength || luigi.getLocation() < raceLength){
mario.randomSpeedChange();
luigi.randomSpeedChange();
if (mario.getLocation() > luigi.getLocation()){
System.out.println(mario + " is in first place at " + mario.getLocation() + "!");
}
if (luigi.getLocation() > mario.getLocation()){
System.out.println(luigi + " is in first place at " + mario.getLocation() + "!");
}
if (mario.getLocation() == luigi.getLocation()){
System.out.println(mario + luigi + "are neck and neck! Who will pull ahead and take the lead?!");
}
}
}
}
import java.util.Random;
public class Car {
private int speed;
private String carName;
private int location = 0;
Random r = new Random();
private int rand;
private static int maxSpeedForAll = 120;
private static int minSpeedForAll = 0;
public Car(int speed, String name) {
this.speed = speed;
this.carName = name;
}
public int getLocation(){
return location;
}
public void setLocation(int location, int speed){
this.location += speed;
}
public static int getMaxSpeedForAll(){
return maxSpeedForAll;
}
public static void setMaxSpeedForAll(int maxSpeedForAll){
Car.maxSpeedForAll = maxSpeedForAll;
}
public static int getMinSpeedForAll(){
return minSpeedForAll;
}
public static void setMinSpeedForAll(int minSpeedForAll){
Car.minSpeedForAll = minSpeedForAll;
}
public int getSpeed(){
return speed;
}
public void setSpeed(int speed){
if(speed <= maxSpeedForAll){
this.speed = speed;
} else {
this.speed = maxSpeedForAll;
}
if(speed < minSpeedForAll){
this.speed = minSpeedForAll;
}
}
public String getName(){
return carName;
}
public void setName(String name){
this.carName = name;
}
public String toString(){
String result;
result = carName;
return result;
}
public void accelerate(int rand){
if (rand > 0){
speed += 10;
}
}
public void decelerate(int rand){
if (rand < 0){
speed += -10;
}
}
public void randomSpeedChange(){
setRand(r.nextInt(10 - -10) + -10);
}
public int getRand() {
return rand;
}
public void setRand(int rand) {
this.rand = rand;
}
}
所以我現在正在做一個任務,我需要在設定的比賽長度上比賽兩輛賽車。爲了確定賽車的當前位置,我必須將賽車的位置值添加到賽車的速度值中,並且該值必須顯示在主賽道上。我認爲很簡單,但是賽車的速度每次在-10到10的時間間隔內都會隨機變化。我一直在爲這幾天做出不同的解決方案,而且我沒有更接近實際做出這一點代碼的工作原理是如何工作的,如果有人能給我一些關於我做錯了什麼的指示,我將不勝感激。在方法中添加一個int,並在主方法中顯示它
總之,我試圖: 1)將整數(位置)添加到整數(速度)並將其返回給主。 2)在將其添加到其他整數(位置)之前,在每個循環中,通過在-10和10之間隨機添加/減去來更改一個整數(速度)。
我提前道歉,如果這是回答已經某處 - 我已經搜索這個網站的高低與解決類似的問題,並不能真正找到任何這是同樣的情況我的問題。