java - JTable读取空值

标签 java swing jtable h2 numberformatexception

我有一个 H2 数据库,我想从 JTable 读取记录来填充数据库表。但是我的表可以有空记录。

我正在使用这个方法:

     String descr = jTable2.getValueAt(i, 1).toString();

每当 JTable (i, 1) 中的字段为空时,我都会收到此错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException.

有什么建议如何从表中读取和存储空值而不出现此错误吗?

编辑: 对于更明确的示例,每当我在空字段中执行 jTable2.getValueAt(i, 1) 时,都会发生相同的 null 异常..

     for (int i = 0; i <10; i++) {

            int processos = Integer.parseInt(jTable2.getValueAt(i, 0).toString());

            String descr = jTable2.getValueAt(i, 1).toString();
            if(!descr.isEmpty())
                 descr = jTable2.getValueAt(i, 1).toString(); 
            else{ 
                 descr= "";
                        }
            //String data = jTable2.getValueAt(i, 2).toString();
            System.out.println(processos + descr);

            try {
                databaseManager.saveTable(intIDinternto, processos, descr, "aaaa");
            } catch (SQLException ex) {
                Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
            }

解决方案:先使用对象,然后解析为字符串并进行比较。

for (int i = 0; i <10; i++) {
        String description = " ";
            int processos = Integer.parseInt(jTable2.getValueAt(i, 0).toString());

            Object descr = jTable2.getModel().getValueAt(i, 1);
            if (descr!= null)
                 description = jTable2.getModel().getValueAt(i, 1).toString(); 
            else
              description = ".";

            //String data = jTable2.getValueAt(i, 2).toString();
            System.out.println(processos + description);

            try {
                databaseManager.saveTable(intIDinternto, processos, description, "aaaa");
            } catch (SQLException ex) {
                Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
            }

最佳答案

您必须进行检查,例如:

String descr = jt.getValueAt(0, 1).toString();
int storedValue = 0;

//check if your value is a correct integer or not
if (descr.matches("\\d+")) {
    storedValue = Integer.parseInt(descr);

} else {
    System.out.println("Exception");
}
System.out.println(storedValue);

想法:使用正则表达式检查您的值是否正确 descr.matches("\\d+") 如果输入正确,那么您可以解析它,否则您不能,您必须抛出异常或其他任何事情

关于java - JTable读取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43633496/

相关文章:

java - JTextField 除非单击否则不会获得焦点

java - 数据更改时刷新 JTable

java - 在拖动列上显示列标题

java - 使用嵌套 for 循环修改二维数组

java - 如何使用 Locale 和 GregorianCalendar 在 Java 中获取给定语言的工作日名称?

java - 如何将图像保存和读取为文本,嵌入到代码中

java - JComponent 的运行时对齐 + 链接到 RowFilters

java - 无法从具有时间戳字段的 datastax 中检索数据

Java 跳过第三个 case 语句

java - 全屏 JFrame 之上的模态 JFrame