为什么我的独立随机对象被分配相同的值?

huangapple go评论97阅读模式
英文:

Why are my separate random objects being assigned the same values?

问题

抱歉,我注意到你的问题中包含了一些代码,但我只提供翻译服务。以下是你要求的代码部分的翻译:

抱歉我怀疑我的问题很容易解决但是我认为为了让它有意义我必须发布的代码相当长所以我道歉如果有一种我不知道的方法可以缩短这个帖子同时仍然让它有意义我会感激反馈

我正在开发一个模拟虚构的4路交叉口First St南北向和Main St东西向的Java程序我想要创建4个Car类的对象使用Math.random()来随机它们的3个属性1. 是否存在2. 它的行驶方向是什么3. 它以什么顺序到达交叉口?),然后将它们打印出来

我确实做到了这一点 - 实例化4辆汽车car1car2car3car4),使用randomizeAll方法随机它们的属性然后使用printState方法打印它们的属性我期望它运行如下

> **Car 1** 这辆车不存在
> 
> **Car 2** 这辆车存在它正在1st St上向南行驶它首先到达
> 
> **Car 3** 这辆车存在它正在Main St上向西行驶它第二个到达
> 
>
> **Car 4** 这辆车不存在

然而它运行得有点像这样的变化
> **Car 1** 这辆车存在它正在Main St上向西行驶它第二个到达
> 
> **Car 2** 这辆车存在它正在Main St上向西行驶它第二个到达
> 
> **Car 3** 这辆车存在它正在Main St上向西行驶它第二个到达
> 
>
> **Car 4** 这辆车存在它正在Main St上向西行驶它第二个到达

所有四辆汽车具有相同的属性尽管每次重新运行程序时它们都会改变)。我无法弄清楚是什么原因导致了这个问题只有两个地方需要查看即CarDemo类中的主方法和Car类本身我的代码如下

**CarDemo类其中包含主方法**

```java
public class CarDemo {

  public static void main(String[] args) {
   
    Car car1 = new Car();
    Car car2 = new Car();
    Car car3 = new Car();
    Car car4 = new Car();
    
    car1.randomizeAll();
    car2.randomizeAll();
    car3.randomizeAll();
    car4.randomizeAll();
    
    System.out.println("Car 1:");
    car1.printState();
    
    System.out.println("Car 2:");
    car2.printState();
    
    System.out.println("Car 3:");
    car3.printState();
    
    System.out.println("Car 4:");
    car4.printState();
    
  }
  
}

Car类,其中包含randomizeAll和printState方法:

public class Car {
    
    private static int existence; 
    private static final int EXISTENCEMAX = 1;
    private static final int EXISTENCEMIN = 0;

    private static int direction;
    private static final int DIRECTIONMAX = 4;
    private static final int DIRECTIONMIN = 1;
    
    private static int order;
    private static final int ORDERMAX = 4;
    private static final int ORDERMIN = 1;

    
    public void randomizeAll() {
        existence = (int)(Math.random() * (EXISTENCEMAX - EXISTENCEMIN + 1) + EXISTENCEMIN);
        direction = (int)(Math.random() * (DIRECTIONMAX - DIRECTIONMIN + 1) + DIRECTIONMIN);
        order = (int)(Math.random() * (ORDERMAX - ORDERMIN + 1) + ORDERMIN);
    }
        
    public void printState(){

    boolean exist;
    exist = existence == 1;
    if (exist) {
        System.out.println("这辆车存在!");
        switch(direction){
            case 1:
                System.out.println("它正在1st St上向北行驶。");
                break;
            case 2:
                System.out.println("它正在1st St上向南行驶。");
                break;
            case 3:
                System.out.println("它正在Main St上向东行驶。");
                break;
            case 4:
                System.out.println("它正在Main St上向西行驶。");
                break;
        }
        switch(order){
            case 1:
                System.out.println("它首先到达。");
                break;
            case 2:
                System.out.println("它第二个到达。");
                break;
            case 3:
                System.out.println("它第三个到达。");
                break;
            case 4:
                System.out.println("它第四个到达。");
                break;
        }           
    } else {
        System.out.println("这辆车不存在。");
    }  
    
  }    
    
}

有人能告诉我为什么每个汽车对象共享相同的值吗?我已经盯着这个问题看了好几个小时,并在网上做了研究,但没有找到解决方法。非常感谢您的任何建议。如果我的代码在某些地方混乱或多余,我深感抱歉,因为我是在我的第一个编程课程的第一个学期,所以我是一个编程新手。提前非常感谢。


<details>
<summary>英文:</summary>
sorry for the long post. I suspect my issue is fairly easy to solve but (I think) the code I must post for it to make sense is quite long in length, so I apologize. If there was a way for me to shorten this post while still having it make sense that I&#39;m not aware of, I&#39;d appreciate the feedback.
I am working on a Java program that simulates a fictional 4-way intersection with stop signs *(First St, which runs north/south and Main St, which runs east/west)*. I want it to create 4 objects of the Car class, randomize their 3 attributes *(1. does it exist? 2. what direction is it traveling? 3. what order did it arrive at the intersection?)* using Math.random(), and print them.
I do exactly this - instantiate 4 cars (car1, car2, car3, car4), randomize their attributes using the randomizeAll method, and then print their attributes using the printState method.. **I expect it to run like this:**
&gt; **Car 1:** This car does not exist.
&gt; 
&gt; **Car 2:** This car exists! It is traveling southbound on 1st St. It arrived first.
&gt; 
&gt; **Car 3:** This car exists! It is traveling westbound on Main St. It arrived second.
&gt; 
&gt;
&gt; **Car 4:** This car does not exist.
Instead, it runs like some variation of this:
&gt; **Car 1:** This car exists! It is traveling westbound on Main St. It arrived second.
&gt; 
&gt; **Car 2:** This car exists! It is traveling westbound on Main St. It arrived second.
&gt; 
&gt; **Car 3:** This car exists! It is traveling westbound on Main St. It arrived second.
&gt; 
&gt;
&gt; **Car 4:** This car exists! It is traveling westbound on Main St. It arrived second.
All four of the cars have the same exact attributes, (although they change each time I re-run the program). I can&#39;t figure out what is causing this. There are only 2 things to look at, my main method in the CarDemo class and the Car class itself. My code is as follows:
**CarDemo class, which contains the main method:**
public class CarDemo {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
Car car4 = new Car();
car1.randomizeAll();
car2.randomizeAll();
car3.randomizeAll();
car4.randomizeAll();
System.out.println(&quot;Car 1:&quot;);
car1.printState();
System.out.println(&quot;Car 2:&quot;);
car2.printState();
System.out.println(&quot;Car 3:&quot;);
car3.printState();
System.out.println(&quot;Car 4:&quot;);
car4.printState();
}
}
**The Car class, which contains the randomizeAll and printState methods:**
public class Car {
private static int existence; 
private static final int EXISTENCEMAX = 1;
private static final int EXISTENCEMIN = 0;
private static int direction;
private static final int DIRECTIONMAX = 4;
private static final int DIRECTIONMIN = 1;
private static int order;
private static final int ORDERMAX = 4;
private static final int ORDERMIN = 1;
public void randomizeAll() {
existence = (int)(Math.random() * (EXISTENCEMAX - EXISTENCEMIN + 1) + EXISTENCEMIN);
direction = (int)(Math.random() * (DIRECTIONMAX - DIRECTIONMIN + 1) + DIRECTIONMIN);
order = (int)(Math.random() * (ORDERMAX - ORDERMIN + 1) + ORDERMIN);
}
public void printState(){
boolean exist;
exist = existence == 1;
if (exist) {
System.out.println(&quot;This car exists!&quot;);
switch(direction){
case 1:
System.out.println(&quot;It is traveling northbound on 1st St.&quot;);
break;
case 2:
System.out.println(&quot;It is traveling southbound on 1st St.&quot;);
break;
case 3:
System.out.println(&quot;It is traveling eastbound on Main St.&quot;);
break;
case 4:
System.out.println(&quot;It is traveling westbound on Main St.&quot;);
break;
}
switch(order){
case 1:
System.out.println(&quot;It arrived first.&quot;);
break;
case 2:
System.out.println(&quot;It arrived second.&quot;);
break;
case 3:
System.out.println(&quot;It has arrived third.&quot;);
break;
case 4:
System.out.println(&quot;It arrived fourth.&quot;);
break;
}           
} else {
System.out.println(&quot;This car does not exist.&quot;);
}  
}    
}
Is anyone able to tell me why each car object shares the same values? I&#39;ve been staring at this and researching online for several hours and nothing pops out at me. Any input is greatly appreciated. I apologize if my code is messy or redundant in some areas, I am in my very first semester of programming classes so I&#39;m the epitome of a programming noob. Thanks a lot in advance.
</details>
# 答案1
**得分**: 0
在“car”类中,我的属性被声明为静态的,这意味着它们在类的所有实例/对象之间是共享的。移除静态关键字解决了这个问题。
<details>
<summary>英文:</summary>
My attributes in the &quot;car&quot; class were declared as static, which means they are shared between all instances / objects of a class. Removing the static keyword fixed the issue.
</details>

huangapple
  • 本文由 发表于 2020年7月22日 15:12:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63028757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定