gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:22:18 26 4
gpt4 key购买 nike

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

我设法将文件读入数组,检查它是否不为空,并根据静态值检查字段长度。我有另一个包含字段大小的数组,但我似乎无法获得交叉引用 dataArrayElement 0 和 valaidateArrayElement 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;
}
}

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

您可以在 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);

希望这有帮助

关于java - 如何使用数组来验证另一个数组中的元素长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38725061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com