-3

I'm making a program which has an option to let the user enter data into an array. For example the option will ask the user to enter the make and model of a car which will then be stored as an element in an array. I want to know how I can let the program enter the next car as a different element each loop. For example:

Loop 1: Enter car details ( stored as myArray[1] )

back to start

Loop 2: Enter car details ( stored as myArray[2] )

etc..

what is the most efficient way to do this?

6
  • 3
    Arrays died long back. Use Collections. Might be List ? Commented Oct 15, 2013 at 12:57
  • doesn't answer the question though Commented Oct 15, 2013 at 12:59
  • You have answers now, Mine is just a comment(suggestion) :) Commented Oct 15, 2013 at 13:01
  • do you know exactly how many cars you have? Commented Oct 15, 2013 at 13:01
  • yes there are 10 cars Commented Oct 15, 2013 at 13:02

3 Answers 3

1

I assume you have object named Car, that contains it's make and mode.
Also I suppose you have method Car readCar() that creats new Car somehow.
See code snipped that creates arraya of Car objects and populates it:

int carsNumber = 10;//number of cars
Car [] cars = new Car[carsNumber];//creates empty array (10 null)
for (int i = 0; i < cars.length; i++)
{
    Car c = readCar(make,model);//creates Car somehow
    cars[i] = c;//populates current car in array, i++ command will move to next index
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much exactly what I needed, just one question where does that 'c' come from at the end?
see previuos line Car c = readCar(make,model);I suppose you know how to create Car object from input data
sorry missed that part ahah thanks
0

Pseudo code:

List<Car> carList = new ArrayList<Car>();
while (userinput!="finish") {
 String detail1 = Console.readline();
 String details2 = Console.readLine();
 Car c = new Car(details1, details2);
 carList.add(c);
}

Comments

-1

Car details?? Better make a class Car and fields accordingly, override hashcode and equals and use Set for sorting purpose.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.