0
    Table table;
    
    class AirPollution{
      String place;
      float NO2;
      float CO;
      int AP;
      
      AirPollution(String p,float x, float y, int c){
        place=p;
        NO2=x;
        CO=y;
        AP=c;
      }
    }


void loadData(){
  String[] data=loadStrings("airPollution.txt");
  AirPollution[] AP=new AirPollution[5];
  for(int i=0;i<data.length;i++){
    //Part I don't know
  }
}

Exactly, I am studying processing. Below is the contents of the txt file

place,NO2(ppm),CO(ppm),Air pollution 
Nowon-gu,0.024,0.6,26
Dobong-gu,0.02,0.4,12
Seocho-gu,0.018,0.3,18
Gwanak-gu,0.022,0.5,20
Guro-gu,0.017,0.3,21

This data exists, and I try to input values ​​from the second line excluding the first line.

For example

AP[0].place="Nowon-gu"
AP[0].NO2=0.024
AP[0].CO=0.6
AP[0].AP=26
AP[1].place="Dobong-gu"

I hope this way. In this case, should I put in each one without using the split function? Or should I use another method?

2 Answers 2

1

I see no reason to not use split.

In your loop, I would first split the current data item on a ,, then just add each part to an AirPollution object which finally gets added to the AP array.

  • Note that in my solution, I initialised your for loop at the index 1 opposed to 0. I'm making the assumption here that loadStrings produces the output that you included, which includes the header row, and I'm assuming that you don't actually want this header row in the AP array.

  • Note that now you might want to put some sort of check to ensure that data.length is greater than 1 before entering the for loop.

  • Note that I've also changed your hard coded array size from 5 to data.length - 1. The assumption here is that the array size shouldn't always be 5, there will always be a header row, and you don't want to include the header row in the array.

The below code should do exactly as you've asked, but see my comment after the code block for some extra points:

void loadData() {
    String[] data = loadStrings("airPollution.txt");
    AirPollution[] AP = new AirPollution[data.length - 1];
    for (int i = 1; i < data.length; i++) {
        String[] dataParts = data[i].split(",");
        AirPollution airPollution = new AirPollution(
            dataParts[0],
            Float.parseFloat(dataParts[1]),
            Float.parseFloat(dataParts[2]),
            Integer.parseInt(dataParts[3])
        );
        AP[i - 1] = airPollution;
    }
}

BUT, from your code, I see that this loadStrings method isn't actually defined in the AirPollution class, you want loadStrings to return void and the loadStrings method doesn't take in any argument. This means, you can populate the AP array just fine with the above code, but your code can't actually do anything with it.

Looking from the code context, I would assume that you want the loadStrings function to actually return the AirPollution array so that you can use it in whatever class is wrapping the AirPollution class. I would make a slight tweek to the above code to reflect this (add return statement and change return type):

AirPollution[] loadData() {
    String[] data = loadStrings("airPollution.txt");
    AirPollution[] AP = new AirPollution[data.length - 1];
    for (int i = 1; i < data.length; i++) {
        String[] dataParts = data[i].split(",");
        AirPollution airPollution = new AirPollution(
            dataParts[0],
            Float.parseFloat(dataParts[1]),
            Float.parseFloat(dataParts[2]),
            Integer.parseInt(dataParts[3])
        );
        AP[i - 1] = airPollution;
    }

    return AP;
}

Let me know if anything is unclear!

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to Ibz' detailed answer (+1) explaining manual parsing, here's a version using Processing's Table class which can be loaded using loadTable():

Table table;

void setup() {
  // load table and specify the first row is a header
  table = loadTable("Airpollution.csv", "header");
  int rowCount = table.getRowCount();
  // for each row
  for (int i = 0; i < rowCount; i++) {
    // access the row
    TableRow row = table.getRow(i);
    // access each piece of data by column name...
    String place = row.getString("place");
    float no2 = row.getFloat("NO2(ppm)");
    float co = row.getFloat("CO(ppm)");
    // ...or column index
    int airPollution = row.getInt(3);
    // print the data
    println(i, place, no2, co, airPollution);
  }
}

Now that you can access the parsed data, you can plug it to instances AirPollution:

Table table;

void setup() {
  // load table and specify the first row is the CSV header
  table = loadTable("Airpollution.csv", "header");
  int rowCount = table.getRowCount();
  // use row count (as .csv data could change)
  AirPollution[] AP = new AirPollution[rowCount];
  // for each row
  for (int i = 0; i < rowCount; i++) {
    // access the row
    TableRow row = table.getRow(i);
    // initialize AirPollution data with row data
    AP[i] = new AirPollution(row.getString("place"),
                             row.getFloat("NO2(ppm)"),
                             row.getFloat("CO(ppm)"),
                             row.getInt(3));
    // print the data
    println("row index",i,"data",AP[i]);
  }
}

class AirPollution {
  String place;
  float NO2;
  float CO;
  int AP;

  AirPollution(String p, float x, float y, int c) {
    place=p;
    NO2=x;
    CO=y;
    AP=c;
  }
  // display nicely when passing this instance to print/println
  String toString(){
    // %.3f = floating point value with 3 decimal places
    return String.format("{ place=%s, NO2=%.3f, CO=%.3f, AP=%d} ", place, NO2, CO, AP);
  }
}

Notice I've renamed the file from .txt to .csv: this extension might help preview/test the data using OpenOffice Calc, Excel, Google Sheets, etc.

Have fun visualising the data. If you want to learn more about the Table class, other the reference, also check out Processing > Examples > Topics > Advanced Data > LoadSaveTable

3 Comments

Nice addition! This looks a bit cleaner IMO and deals with the header row much more gracefully (+1)
Thank you. This is just using the built-in Table class. Explaning your method to manually parse CSV data is useful because bovet can later apply the exact same logic if using other programming languages down the line.
It is a little late, but thank you very much. I get to know a lot thanks to your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.