如何使用数组验证另一个数组的元素长度?

时间:2016-08-02 15:45:47

标签: java arrays

我正在尝试创建一个文件验证器,因此,导入一个csv文件,检查内容,检查每个字段是否为空,然后检查每个字段的长度。如果它大于指定值(每个字段不同),那么我想将其显示为不同的颜色,以便我可以轻松识别任何不适合我的数据库的字段。

我设法将文件读入数组,检查它是否为空,并检查字段长度是否为静态值。我有另一个包含字段大小的数组,但我似乎无法使用valaidateArrayElement 0获得交叉引用dataArrayElement 0。

我已将它输出到JTable,并显示任何以不同颜色点击“TOOBIG”的内容。

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;
    }
}

对此有任何帮助将不胜感激!

由于

1 个答案:

答案 0 :(得分:0)

您可以在validate方法中传递数据元素的索引,并检查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";
      }
  }

在调用此方法时,传递索引(假设要验证的值是跨列)

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

希望这有帮助