如果持续出现错误该怎么办:包围范围内定义的局部变量j必须是final或有效的final

问题描述 投票:0回答:1

我正在尝试读取位置(i)上有多少行,并按Enter键分隔显示,在(j)时刻显示哪一行-按15的示例1时,按Enter键将显示15的2行这是导致错误的部分代码:

int i = 0;
        int j = 0;


        try {
            ResultSet rs = stmt.executeQuery("SELECT * FROM product WHERE Location = 'REC1U'");
            while(rs.next()) {
                i++;
            }
            rs.next();
            tfield.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                        j++; // <--- this is causing above error
                        String l = String.valueOf(j);

                        count.setText(l);
                    }
                }

                });
        } finally {
            stmt.close();
        }

我已经尝试将其最终定为试图摆脱它,但是反正还是行不通的...

java database counter keylistener
1个回答
0
投票

您可以使用内部带有最终计数器的对象。例如:

final AtomicInteger j = new AtomicInteger(0);

//...
public void keyPressed(KeyEvent e) {
    j.incrementAndGet();
}

0
投票

尝试一下

tfield.addKeyListener( e ->
                {
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    j++; // <--- this is causing above error
                    String l = String.valueOf(j);
                    count.setText(l);
                }
               });
© www.soinside.com 2019 - 2024. All rights reserved.