【问题标题】:Java For Loop as an argumentJava For 循环作为参数
【发布时间】:2015-11-28 15:30:21
【问题描述】:

我一直在尝试做这个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) 给我一个错误,说“我”必须是最终的或有效地最终的。这是 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"};

如果你能帮助我,我可以继续我的项目。

谢谢。

【问题讨论】:

    标签: java arrays function for-loop try-catch


    【解决方案1】:

    您可以定义另一个局部变量,将其声明为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");
            }   
        });
    }
    

    【讨论】:

    • 谢谢哥们,我脑子里放了个屁,没想到是这样的!你太棒了!
    【解决方案2】:

    i 必须是 final,因为匿名内部类不能使用外部变量,除非它是 final

    在没有final 的情况下可以使用它的唯一情况是,如果它直接传递给被匿名类子类化的类的构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 2011-08-28
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多