Results 1 to 3 of 3
  1. #1
    diskhub is offline Member
    Join Date
    May 2010
    Posts
    25
    Rep Power
    0

    Default Dynamic Create Object based on user's input?

    If the following line is for me to create a Car object,

    Car car1 = new Car();

    How can I create a dynamic list of car based on the user's input?
    For example, if user enters 5,
    I wish to do the following:

    Car car1 = new Car();
    Car car2 = new Car();
    Car car3 = new Car();
    Car car4 = new Car();
    Car car5 = new Car();

    I wish to be able to randomly assign color to the cars like this:

    for(int i=1; i<6; i++){
    ... //not sure how can I concatenate 'car' with the number...
    }


    How can I do so?

    Should I create an array of Car with the size inputted by the user?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,830
    Rep Power
    19

    Default

    Yes.
    You are creating an array of cars of whatever size the user has enetered.
    Or a List<Car> if you don't know how many the user is going to create (and you've covered Collections and generics).

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    to chooser random colors you can also create an array to hold the colors and randomly index into the array to get the colors to set the car's color variable

    Java Code:
    Color[] colors = { Color.black, Color.red, Color.green };
    Random rand = new Random();
    combine colors and random in the car constructor.
    I gave you way more than you need to solve this(I ma have given more than I should have)

Similar Threads

  1. Displaying a square based on user's input
    By luke in forum New To Java
    Replies: 15
    Last Post: 07-14-2012, 09:43 AM
  2. Replies: 5
    Last Post: 07-09-2010, 06:14 AM
  3. Replies: 2
    Last Post: 06-22-2010, 04:29 AM
  4. How to create dynamic string object???
    By Stephen Douglas in forum New To Java
    Replies: 8
    Last Post: 04-12-2010, 02:35 AM
  5. Replies: 1
    Last Post: 01-23-2009, 04:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •