So I need to create Object for example called Car containing - String car model - int count - String percentage
After getting this data how do I put all Car Objects into for-loop of Objects to get Arraylist of all Car objects?
So I need to create Object for example called Car containing - String car model - int count - String percentage
After getting this data how do I put all Car Objects into for-loop of Objects to get Arraylist of all Car objects?
You could do:
List<Car> carList = new ArrayList();
for(int i = 0; i < numberOfDesiredCars; i++){
Car c = new Car(arguments);
carList.add(c);
}
I don't understand what the question is? Can you be a little more specific? Are you saying you want all your objects into a list? If so, you'd either add each one individually or you could do
carList.addAll(Arrays.asList(carObject1, carObject2, and so on));
I don't know what you mean about put them all into a for loop after that. What's the for loop being used for? Are you just wanting to print all of them? If so, you wouldn't need a for loop to print the entire list, just if you wanted to print ones that meet only a certain criteria.
You will need to provide some code for us to help you directly, but to do what you say, it will be best to generally have two separate files.
In one file:
//Car.java
public class Car{
private String model; //instantaneous variables
private int count;
private String percentage;
public Car(){ //default constructor
model = "whateverModelName";
count = 123;
percentage = "75";
}
public Car(model,count,percentage){ //custom Constructor with parameters
}
Then in another file: CarRunner.java:
//carRunner.java
public class carRunner{
public int numOfObjects = 0;
public static void main(String[] args){
//Creates Car objects and initializes object name to "car1", "car2", etc.
//Add code that adds 1 to numOfObjects each time an object is created
getArrayList(); //calls getArrayList method
}
public static void getArrayList(){
//creates and initializes your arrays to the proper sizes
String[] model = new String[numOfObjects];
String[] percentage = new String[numOfObjects];
int[] count = new int[numOfObjects];
for (i=1;i<=numOfObjects;i++){
model[i] = car + i + .model; //not sure how to do this actually, if someone can help write this to get the different variables from different objects
}
for (i=1;i<=numOfObjects;i++){
percentage[i] = car + i + .percentage; //not sure how to do this actually, if someone can help write this to get the different variables from different objects
}
for (i=1;i<=numOfObjects;i++){
count[i] = car + i + .count; //not sure how to do this actually, if someone can help write this to get the different variables from different objects
}
}