Question
need help with this array problem. Hope someone can help me. File Input & Arrays You have been hired by a company to write a
need help with this array problem. Hope someone can help me.
File Input & Arrays
You have been hired by a company to write a program that will read in a set of locations from a text file and display certain information about the data set.
Concepts
Arrays
File input
working more with defining objects
Remember, it's ok to ask questions to clarify things. That's part of the analysis phase of the SDLC. Please submit your solution in one .zip or .jar file
User Interface
Here is user interface client code that you can use to work with your supplier classes.
Input Data Files and storage
The text file your program will read from must follow this format:
start with one integer on its own line
followed by a series of lines. Each line contains 3 pieces of information: a location name (a single word) then latitude (lat) and longitude (long) pairs of doubles. The data on the lines are separated by spaces. The very first line is how many lines of information are in the file.
Latitude measures the number of degrees north or south from the equator (0 degrees) We will use signs to identify north (positive) or south (negative). The maximum value is 90 degrees, the minimum value is -90 degrees. For example, Seattle's latitude is 47.60835430674681 the latitude of McMurdo Station (Antarctica) is -77.85
Longitutude measures the number of degrees east or west from the Greenwich Meridian (a line that goes from pole to pole around the earth through Greenwich, England). Positive longitudes are east of this meridian; negative longitudes are west of this meridian. The max is 180, the min is -180
Here are the lat/long for Seattle and McMurdo Station:
Seattle Latitude: 47.67340087890625 Longitude: -122.34259796142578
McMurdo Station Latitude: -77.85 Longitude: 166.6666667
Here is a good site to find latitude/longitude for different locations. Here's another site. You can also read more about latitude and longitude here.
You program does not have to be responsible for files that do not match this format (in other words, if the end user gives you a filename with bad data and the program crashes, that's ok). You can create any text file you want for testing (use a program like Notepad or any other basic text editor). Here are some files I've created for you to use: locations1.txt or locations2.txt Make sure to look at and run the example programs that illustrate reading data from a file.
Code Specification
Implement the class specifications below. To get full credit, your program's public interface must match these descriptions exactly.
class Location |
You decide your instance variables |
+ Location(String name, double lat, double lon) -- initializes this Location object with the given name, and lat/long in degrees. Throws an IllegalArgumentException for invalid values.
+ double getLatitude() -- returns the latitude of this location + double getLongitude() -- returns the longitude of this location + String getName() -- returns the name of this location + String toString() -- returns a String representation of this Location + double distance(Location l) -- returns the distance between this Location and the parameter. The algorithm is discussed below. |
Distance Calcuation
To find the distance between two locations on the planet, we'll be using the Haversine Formula. This is a pretty complex calculation, so I'm giving you code to start with. Assume we have the lat/long of 2 locations, in degrees:
// earth's radius, in miles double earthRadius = 3963.1; // convert all angles to radians. Radians is another unit for measuring angles. Needed for trig methods lat1 = Math.toRadians(lat1); // notice I'm reusing variables here. You probably won't want to do this in your solution. lat2 = Math.toRadians(lat2); lng1 = Math.toRadians(lng1); lng2 = Math.toRadians(lng2); // calculate the Haversine formula in pieces double dLat = lat2-lat1; double dLng = lng2-lng1; double sindLat = Math.sin(dLat / 2); double sindLon = Math.sin(dLng / 2); double a = Math.pow(sindLat, 2) + Math.pow(sindLon, 2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); double dist = earthRadius * c;
The final answer is in the variable dist. Use this algorithm in your distance() method. When I was testing this code, I used this site to confirm my solutions http://jan.ucc.nau.edu/~cvm/latlongdist.html
The other file to implement is this:
class GeoSet |
You decide your instance variables. The one requirement is to use an array to hold all the Location objects. |
+ GeoSet(String filename) throws FileNotFoundException-- initializes a GeoSet object using the data from the specified file name, where the file follows the format described above. The precondition is that the file must contain at least 2 lat/long pairs. Throw an IllegalArgumentException otherwise. + int getCount() -- returns the number of Locations in this set + double findMinDist() -- Based on the order that the Locations were loaded into this GeoSet, this method returns the smallest distance between 2 consecutive Locations in this set. + Location find(String name) -- returns the Location whose name matches the parameter. Return null if no match found. + Location[] farthest() -- returns an array with the 2 Locations from this GeoSet that are the farthest from each other. These 2 Locations are not necessarily consecutive in the set. + String toString() -- returns a String that contains the String representation for each Location object in this GeoSet, separate by ' '. |
Suggestions
I hope by this point in the quarter you appreciate the benefit of working pieces of your solution one at a time. I recommend building and testing your Location class first. Next work on reading in the data (the GeoSet constructor method). Then tackle one or two methods at a time.
If it makes sense to decompose any of these methods, do so. However, the helper methods should all be private. Only these methods listed here should be part of the public interface.
Also, when dealing with the FileNotFoundException, every method that calls the GeoSet constructor needs the throws clause in its method signature (unless you want to use try/catch blocks in the any client code, but that is not a requirement for this assignment).
Documentation and Style
Make sure to write complete Javadoc comments for each class and each public method.
Include sufficient internal documentation.
Use appropriate style (variable names, indenting, class constants, etc.) throughout the program.
Be wise in your choice of instance variables. Only the data that an object needs to know (and remember) should be an instance variable.
Grading /15 Program works and contains the proper methods. Good overall design. /5 documentation, style
Good Luck!
EXTRA CREDIT
(1 point) Update your Location class to allow clients to specify degrees, minutes, and seconds as an alternative to decimal latitude and longitude. The format of latitude is a String of the form: "dd mm ss H" where dd is degrees, mm is minutes, ss is seconds, and H is hemisphere, holding N or S depending on whether this is North or South of the equator. All 4 pieces of information will be separated by whitespace. For example, here are two different latitudes:
47 36 23 N (Seattle) 77 50 60 S (McMurdo Station in Antarctica)
The format for longitude is similar: dd mm ss followed by E or W, depending on whether it is East or West of the Greenwich meridian (meridian 0). Here now are the complete lat/long for Seattle and McMurdo Station:
Seattle 47 36 23 N 122 19 50 W
McMurdo Station 77 50 59 S 166 40 0 E
Perform input validation on these Strings, just as you did for the decimal degrees. There are useful methods in both the Scanner class and the String class to help split up a String.
(1 point) Under the suggestions, I specify that helper methods should be private, not public. Explain the reason why you hide these methods from a client. You may put your answer into the block comments at the top of the GeoSet class. Please make it obvious to me, such as a heading in the comments: EXTRA CREDIT.
here is the locations1.txt file:
4 NSCC 47.699480 -122.333536 Paris 48.860861 2.336419 NYC 40.747923 -73.985217 DisneyLand 28.381646 -81.563761
here is the locations2.txt file: 10 Cairo 30.044420 31.235712 London 51.508129 -0.128005 Boston 42.358431 -71.059773 GoldenGateBridge 37.818549 -122.478676 GrandCanyon 36.055761 -112.137451 Seattle 47.67340087890625 -122.34259796142578 Antarctica -77.85 166.7 PanamaCanal 9.250548 -79.876099 CapeTown -33.934245 18.369141 Seville 37.3898 -5.976563
Here is the client code:
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; /** * Client App * * @author (your name) * */ public class GeoApp { private JTextArea text; /** * Constructor for objects of class GPSApp */ public GeoApp() { JFrame win = new JFrame("142 GEO App"); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); win.setSize(500, 400); // Create the button JButton button = new JButton("Load Data"); // put button in a panel and then into the frame JPanel back = new JPanel(); back.setBackground(Color.blue); back.add(button); win.add(back,BorderLayout.SOUTH ); // now set up the event handler button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ process(); } }); // create the display area and place it text = new JTextArea(); JScrollPane scrolltxt = new JScrollPane(text); win.add(scrolltxt, BorderLayout.CENTER); // get the frame ready to show win.validate(); win.setVisible(true); win.toFront(); } // processing the button click private void process(){ // get filename from user JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION){ String filename = fc.getSelectedFile().getPath(); // create a LocationSet and display results try { GeoSet gs = new GeoSet(filename); String results = buildDisplay(gs); text.setText("File:\t" + filename + " "); text.append(results); } catch (FileNotFoundException e){ text.setText("Sorry, file not found Please try again"); }catch (IllegalArgumentException e) { text.setText("Sorry, file must have at least 2 locations Please try again"); } } } // build & return String for display using information from ls private String buildDisplay(GeoSet gs) { StringBuilder output = new StringBuilder(); Location lookUp = gs.find("Seattle"); Location[] furthest = gs.farthest(); double minD = gs.findMinDist(); output.append("Number of locations = " + gs.getCount() + ' '); output.append("Min distance (mi) = " + minD + " "); output.append("Farthest Locations \t" + furthest[0] + " \t" + furthest[1] +" "); output.append("\tdistance (mi) \t= " + furthest[0].distance(furthest[1]) + " "); if (lookUp !=null){ output.append("Seattle found: \t" + lookUp); } else { output.append("Seattle not found"); } output.append(" ========================== "+ gs); return output.toString(); } public static void main(String [] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { GeoApp b = new GeoApp(); } }); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started