简体   繁体   中英

Retrieve value from a one-dimensional array Jave

I have created a program containing of multiple classes where one class asks how many times to run the program and then creates an array of multiple scanner input-values from another class each time the program is run. (The values are vehicle, name and years, and these are accessible with getVehicle, getName, getYears)

I can manage to print out the arrays depending on how many times the program is running using this code:

for(int i=0;i<array1.length; i++) {
    System.out.println(array1[i]);
} 

but I would also like to print out one specific array-element from each array. Lets say the arrays are:

[car, James, 2]
[bus, Anna, 3]. 

How can I access the numbers 2 and 3 (years)? I can't seem to know how to call the elements no matter how much I try. When I call theclass.getYears() in the loop I only get the last input but not the elements from both arrays.

I am not sure if I understand correctly but if your array consists of objects then what you could do is

for(int i=0;i<array1.length; i++) {
    System.out.println(array1[i].getYears());
} 

You are not very clear about your issue. But I have an idea.

When you are creating your arrays, you can add the "Years" value to an arrayYears so you can access all your years data.

Then you might just print the arrayYears with this:

for(int i = 0; i < arrayYears.length; i++) {
    System.out.println(arrayYears[i]);
}

You might add all the vehicle arrays to an array of all te vehicles! Then you just use:

int n = numberOfVehicles;

for(int j = 0; j < n; j++) {
 
   System.out.println(allVehicles[i][2]);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM