Solved

value in first position of one array overwritten by value in second array

Posted on 2007-04-01
6
211 Views
Last Modified: 2013-11-23
Hi,
I have the following code(below), I want to create two arrays which simulate roads. The "road" has a particular type of car at position [0] in one road and another type of car in position[0] in the other road. There is no connection between the two roads apart from they are arrays of car objects. Unfortunatley, when I populate the array, the first roads firat car is overwritten by the type of car in the second array and I just cant understand why.
I am new to java, so am just trying to get my head round it.
Any help greatly appreciated
Cheers
John

import java.util.*;

public class car
      {
      public static String name = new String();
      public Ship(String Carname)
            {
            name= Carname;       
            }
      }

import java.util.*;

public class CarSim
      {
      public static void main(String[] args)
            {
                  Car[] Road1 = new Car[100];
                  Car[] Road2 = new Car[100];
                  Road1[0].name="Fiat";
                  Road2[0].name="Renault";
                  System.out.println(Road1[0].name);
                  System.out.println(Road2[0].name);
            }
      }

0
Comment
Question by:jdav3579
  • 2
  • 2
  • 2
6 Comments
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 18831857
Post the full code, the code you have shown would throw a NullPointerException "Road1[0].name="Fiat";" here
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 18831885
> public static String name = new String();

I think this field should be non-static. static fields are same on all the instances of the class. So, change that to

public String name = new String();
0
 

Author Comment

by:jdav3579
ID: 18831911
Hi Ajay-Singh,
Thanks for your comments.
This is the full code, obviously over 2 files, but thats the whole thing. It doesnt throw any exceptions though. It just shows renault for both arrays at position zero where one array should have fiat!
I am also not sure what you mean about the non-static field and how that works?
Cheers
John
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 18831935
Optimized version of your current code. It uses a linkedlist which does not have the restriction of size. It's just to give you an example of how such a thing could be programmed. I included comments on most of the lines, it also uses generics (you might have heard of it), i wouldn't worry too much about that, if you want I can give the same example without generics.

There are many ways in which things can be programmed, this is just to show you one.

//CarSim.java
import java.util.LinkedList;

/**
 * A car simulator, which defines two roads as list of cars.
 */
public class CarSim
{
    /**
     * Program entry.
     *
     * @param   args    command line arguments
     */
    public static void main(String[] args)
    {
        //Create two roads, actually two list which can contain Car objects
        LinkedList<Car> road1 = new LinkedList<Car>();
        LinkedList<Car> road2 = new LinkedList<Car>();

        //Add a Car with name "Fiat" to road 1 and a Car with name "Renault" to road 2
        road1.add(new Car("Fiat"));
        road2.add(new Car("Renault"));

        //Print the first element in the list
        System.out.println(road1.get(0).getName());
        System.out.println(road2.get(0).getName());
    }
}

//Car.java
/**
 * A car simply contains a name.
 */
public class Car
{
    private String name;

    /**
     * Construct a Car from a given name.
     *
     * @param   name    name of the car
     */
    public Car(String name)
    {
        this.setName(name);
    }

    /**
     * Returns the name of the car.
     *
     * @return  name of the car
     */
    public String getName()
    {
        return this.name;
    }

    /**
     * Sets the name of the car.
     *
     * @param   name    name of the car
     */
    public void setName(String name)
    {
        this.name = name;
    }
}

---Instruction---
Compile with:
    javac *.java -d .
Run with:
    java CarSim

Good luck,
Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18831963
Static vs non-static

Let me tell you a very basic story on how you can look at this.
You have several types of containers, for example a square, rectangle, sphere, etc. Now assume that we can create these containers. We only have to specify what type of container we want to create. So if i want a square container, then i say: new Square(); . This will create a Square container for me in which I can put stuff, for example other containers or just some values. If i pick the container up and play around with it, then the stuff inside is also moving, but what if I want to have some sort of counter for how many containers I created? I can't put this inside one container, since then other containers will depend on that container. So switching to java now..

Assume we want 3 containers, two squares and one sphere. I would do the following:

Square square1 = new Square();
Square square2 = new Square();
Sphere sphere1 = new Sphere();

Now if I want to add some value to the first square1 container, then I would assume it defines some possible values for me (for example a color) and I can set this color, for example:

square1.setColor("Red");

Now if we look at the definition of this Square type, then we need to have some variable to store this color. So A basic definition looks like:

class Square
{
    private String color;
    //Construct a Square container
    public Square()
    {
        this.color = "White"; //here we can set a default color
    }
   //This method will set the color of this container
   public void setColor(String color)
   {
       this.color = color;
   }
}

Now if we play around with this square1 object, then the color will move with it. The variable color (in the Square class) is said to be non-static, or a member variable of the Square class.
What does it mean if we make this variable static? Well this variable will then be shared over all the Square type containers! So if we modify this variable somewhere, it will modify for all! So normally you do not want that, and therefore you create new instances of an container (object) with the new keyword.
So if I say: new Square(), it really means, make a new container for me, initialize it with default values and variables which I can individualy set.
Ok, small summary:

Assume two objects:
Square square1 = new Square();
Square square2 = new Square();

and the Square class defines two variables:

public static String name;
public String color;

Now if we say:
square1.name = "Fiat";
square1.color = "red";

then the result is:
square1.name equals "Fiat"
square2.name equals "Fiat"
square1.color = "red";
square2.color = "white"; (white is the default value)

I hope it's clear now.. if not, search on google for static vs non-static for more examples and more explanation. Or of course, ask us. :-)
Mark
0
 

Author Comment

by:jdav3579
ID: 18832110
Mark,
That is fantastic! I have been trying to understand how it works, and you have made it very clear to me.
Your help has been invaluable.
Again many, many thanks.
John
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Exchange and Third Party application. 8 60
stringclean challenge 26 58
groovy example issue 10 70
solarwind tftp server 2 32
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now