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;
}
}
所以我目前正在做一项任务,我需要在设定的比赛长度内比赛两辆车。为了确定赛车在比赛中的当前位置,我必须将赛车位置值与赛车速度值相加,并且该值必须显示在 main 中。我想这很简单,但是每次比赛循环时,汽车的速度都会以 -10 到 10 的间隔随机改变。几天来我一直在研究不同的解决方案,但距离真正实现这个还差得很远。代码按其应有的方式工作,如果有人能给我一些关于我到底做错了什么的指示,我将不胜感激。
总而言之,我正在尝试: 1)将一个整数(位置)与一个整数(速度)相加,然后返回到main。 2) 在每次循环期间通过在 -10 和 10 之间随机加/减来更改一个整数(速度),然后将其添加到另一个整数(位置)。
如果这个问题已经在某个地方得到了回答,我提前表示歉意 - 我在这个网站上到处搜索类似的问题和解决方案,但找不到任何与我的问题相同的情况。
最佳答案
可能的结果需要注意以下几点:
- 确定
rand
的值后,您应该检查是否调用accelerate
或decelerate
。这些方法应该仅修改速度
的值。 accelerate
和decelerate
应使用speed
的修改值作为参数来调用setSpeed
。- 设置速度后,应调用
setLocation
。如果不使用setLocation
方法中的location
参数,则无需将其列为形式参数。
关于java - 在方法中添加一个int并在main中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427589/