1

I have a CSV file that I am reading from. I have created a constructor with six arguments for initialising the six fields and a public string method to convert a string into the format I need.

public Hill(int number, String name, String countyName, double height, double latitude, double longitude) {
    this.number = number;
    this.name = name;
    this.countyName = countyName;
    this.height = height;
    this.latitude = latitude;
    this.longitude = longitude;
}

Now what I am trying to achieve is after opening the file and reading it, it creates the corresponding object and then to return the list of the items.

I was given an inital method of public static List<Hill> readHills()

I have commented out a line which i tried to create a new object from simply because I wasn't sure if I was doing it right, so i just printed out as a test to see what my code was doing and it seems that the new object line is redundant. Currently my code is:

public static List<Hill> readHills() {
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/TOSHIBA/Desktop/hills.csv"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Scanner finalFileName = fileName;
    List<Hill> list = new ArrayList<Hill>() {
        {
                for(int i = 0; i < 21; i++) {
                    String line = finalFileName.nextLine();
                    String[] splitted = line.split(",");
                    //add(new Hill(1, "", "", 100, 100, 100));
                    System.out.println(Arrays.toString(splitted));
                }

            }
    };
    return list;
}

In the code where I create the object I put a sample value but technically I want the 6 fields of the new object to be from the file I read. If i try adding the field names, i get a red line saying Non static method cannot be referenced from a static method

Where am i going wrong? And why is my line of code useless?

I continued trying to play with the code but can't get anywhere, I think my issue is not understand the method name i have been given; i.e. Why and what does public static List<Hill> readHills() do?

I tried using Hill newHill = new Hill( int number, String name, String countyName,double height, double latitude, double longitude); but can't since I cant reference a non-static field from a static context

  • http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context – TmTron Mar 31 '17 at 13:48

1 Answers1

2

For starters: this here

List<Hill> list = new ArrayList<Hill>() {

is valid syntax, but not at all what you want.

Just go for:

List<Hill> list = new ArrayList<>();

instead. What you are doing creates an anonymous inner class; and that is totally not required here; and instead leading to many of the issues you see.

Then: you have to turn your strings into the correct type:

 String[] splitted = line.split(",");

gives you an array of String objects. You have to convert those; so that you can pass them to the constructor accordingly (your constructor expects an int value as first parameter, not a String for example!)

Hill hill = new Hill(Integer.parseInt(splitted[0]), splitted[1], ...

and so on.

And then you do:

list.add(hill);

But the tricky part is: such parsing relies on "correct" input. So you should be prepared for all kinds of error handling.

And beyond that: unless this is homework, then do not implement your own CSV parser. Use some existing library for that (see here for ideas). You see: doing correct CSV parsing, that works with all the subtle quirks of this format is not easy. You can easily spend hours on this task; to then find that the next CSV file you work with ... contains yet another (valid!) variation of CSV input that breaks your self-written parser. (believe me, I have been there)

And finally: if such things already overburden you, then the real takeaway is: accept that you are not there yet. Step back; get back into learning mode and understand all those basic Java things.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I see, but since i start of my code like `List list = new ArrayList() {` my list isnt initialized. So should i rewrite my code in a different format? Because i would've though my list is initialised. –  Mar 31 '17 at 13:55
  • See my updates; I just realized that you have a *gross* syntax mistake in your code which causes most of your trouble. – GhostCat Mar 31 '17 at 13:57
  • Yes, and another downvote. Please speak up. I have no idea why you think this answer deserves a downvote. – GhostCat Mar 31 '17 at 13:58
  • Hmm, Since my CSV has a row which corresponds to what the remaining rows it has, For example "Number" which is a string, but starting from the 2nd row, they correspond to the actual types we define i.e. as an Int it will get an error. So that means i have to start from the second row? –  Mar 31 '17 at 14:05
  • For example. As said: there are **many** subtle things that make csv parsing hard. Column headers are one of them. – GhostCat Mar 31 '17 at 14:06
  • Would a workaround be, using a for loop to start at 1 uptil the length of how many rows there are?. Because I changed my code a bit, removing the for loop and adding a while loop to go through each line (using `while fileName.hasNextLine` –  Mar 31 '17 at 14:08
  • I also noticed that since some of my values are doubles, the code needs to be `Double.parseDouble`. –  Mar 31 '17 at 14:33