Wikipedia:Reference desk/Archives/Computing/2024 May 4
Appearance
Computing desk | ||
---|---|---|
< May 3 | << Apr | May | Jun >> | May 5 > |
Welcome to the Wikipedia Computing Reference Desk Archives |
---|
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages. |
May 4
[edit]How do I write this road trip?
[edit]On the Data Structures unit of a CodeHS course, there’s a part where I’m supposed to write a road trip in Java. The GeoLocation class was mostly autogenerated (requiring just a few additions that I already made) and most of the RoadTrip class seems simple. It wants me to store the stops on the road trip in an ArrayList, so I wrote “private ArrayList<RoadTrip> stations;”. The part where I’m having an issue is the function “public void addStop(String name, double latitude, double longitude)”. How do I write this part, and how do I add the stops to the ArrayList with “stations.add();”? ArrayLists only have one dimension, but I need to store three pieces of information about each stop. Primal Groudon (talk) 14:22, 4 May 2024 (UTC)
- Making RoadTrip an array implies that you are working with a bunch of road trips. It appears that you have one road trip and you want to have multiple stops. So, your road trip object/class should contain an array of stops. This is the basic concept of relationships. In your example, you claim that a road trip "is a" array of stations. But, in reality, a road trip "contains" or "has a" array of stations. The whole "is a" and "has a" relationship concept is difficult for new object-oriented developers, but it is supposed to be simplified by filling in the sentence: A road trip ____ an array of stations. 12.116.29.106 (talk) 15:54, 7 May 2024 (UTC)
- To add to the great comment above, you would want to have a Stop class, which contains a Stop class object with instance variables name, latitude, and longitude. Then in the RoadTrip class you could create an ArrayList named "private ArrayList<Stop> stations", which you can then use to load the aforementioned instance variables into the ArrayList with the method “public void addStop(String name, double latitude, double longitude)”. In this case, you will only need to write your method to access the Stop object at the desired index, then change the attributes of that Stop object and not the entire RoadTrip class.
- Hope this is useful! Hanoi2020 (talk) 08:18, 12 May 2024 (UTC)
- Thank you. Primal Groudon (talk) 01:05, 19 May 2024 (UTC)