Java For 循环作为参数

标签 java arrays function for-loop try-catch

我一直在尝试制作这个for循环

    for ( int  i = 0; i < Main.ipList.length; i++){
        JButton btn = new JButton();
        btn.setText(Main.ipList[i]);

        panel.add(btn);
        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                Main.refreshSpecificIp(i);
                System.out.println("Bu");
            }   
        });
    }

Main.refreshSpecificIp(i) 给我一个错误,说“i”必须是最终的或有效的最终的。这是refreshSpecificIp函数:

 public static void refreshSpecificIp(Integer d){
        try
        {
            InetAddress inet = InetAddress.getByName(ipList[d]);
            System.out.println("Sending Ping Request to " + ipList[d]);

            boolean status = inet.isReachable(500000); //Timeout = 5000 milli seconds

            if (status)
            {
                System.out.println("Status : " + ipList[d]+ " Host is reachable");
            }
            else
            {
                System.out.println("Status " + ipList[d]+ " Host is not reachable");
            }
        }
        catch (UnknownHostException e)
        {
            System.err.println(ipList[d] + " Host does not exists");
        }
        catch (IOException e)
        {
            System.err.println(ipList[d] + " Error in reaching the Host");
        }
    }
    static String[] ipList = {"127.0.0.1", "173.57.51.111", "69.696.69.69"};

如果可以的话请帮助我,以便我可以继续我的项目。

谢谢。

最佳答案

您可以定义另一个局部变量,将其声明为final,然后将i的值赋给它:

for ( int  i = 0; i < Main.ipList.length; i++){
    JButton btn = new JButton();
    btn.setText(Main.ipList[i]);
    panel.add(btn);
    final int j = i;
    btn.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            Main.refreshSpecificIp(j);
            System.out.println("Bu");
        }   
    });
}

关于Java For 循环作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973054/

相关文章:

java - 新更新后如何安装oracle-java8-installer

java - 有效地比较 Java 对象列表中的检查映射

c - 如何找出分配一个字符数组的空间大小

c - 将文件的行存储为c中的结构数组

c - 在 C 中传递和返回数组

javascript - 循环不会搜索整个对象数组吗?

java - 当拦截器存在时,EJB 注入(inject)失败

c - 在 C 中对结构体数组中的元素进行排序

c - 一种在不知道签名的情况下包装 C 函数调用的方法?

java - File.mkdirs() 是否需要 WRITE_EXTERNAL_STORAGE 权限