Dan Dan - 4 months ago 8
Java Question

How can I use an array to validate an element length from another array?

I'm trying to create a file validator, so, import a csv file, check the contents, check each field isn't blank, then check the length of each field. If it's bigger than a specified value (different for each field), then I want to display it as a different colour, so that I can easily identify any fields that won't fit into my database.

I managed to read the file into an array, check that it's not null, and check the field length against a static value. I have another array containing the field sizes, but I can't seem to get cross reference dataArrayElement 0 with valaidateArrayElement 0.

I've got it outputting to a JTable, and displaying anything that hits "TOOBIG" in a different colour.

Integer[] validateLength = {8,2,22,11,25,13,6,2,34,11,35,35,34,11,1};

class checkValue{
public String validate(String value){
// Check to see if the cell is null or blank
if (StringUtils.isNullOrBlank(value)) {
return "EMPTY";
} else if (value.length() > 8) { //Work out how to set this as differing field lengths
return "TOOBIG";
}
else {
return "OK";
}
}
}


class CustomRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 6703872492730589499L;
private checkValue cv = new checkValue();

public JComponent getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JComponent cellComponent = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (cv.validate(table.getValueAt(row, column).toString()).equals("TOOBIG")){
cellComponent.setBackground(Color.RED);
cellComponent.setForeground(Color.YELLOW);
cellComponent.setToolTipText("Data is too big for the DB");
} else if(cv.validate(table.getValueAt(row, column).toString()).equals("EMPTY")){
cellComponent.setBackground(Color.GRAY);
cellComponent.setForeground(Color.WHITE);
cellComponent.setToolTipText("Field is empty in import file!");
} else {
cellComponent.setBackground(Color.WHITE);
cellComponent.setForeground(Color.BLACK);
}
return cellComponent;
}
}


Any help on this would be appreciated!

Thanks

Answer

You can pass index of your data element in validate method and check corresponding value from validateLength

    Integer[] validateLength = {8,2,22,11,25,13,6,2,34,11,35,35,34,11,1};

    public String validate(String value, int index){
    // Check to see if the cell is null or blank
    if (StringUtils.isNullOrBlank(value)) {
        return "EMPTY";
    } else if (value.length() > validateLength[index]) { 
        return "TOOBIG";
      }
      else {
        return "OK";
      }
  }

And while calling this method pass the index (assuming values to validate are across columns)

validate(table.getValueAt(row, column).toString(), column);

Hope this helps