为什么变量n在Java中的第二个侦听器中不可见?

时间:2016-03-15 13:38:22

标签: java variables listener visible

我不知道为什么变量n在第二个侦听器中不可见。一切都在问题中。下面我添加一个代码。这只是所有源代码的一部分。

ActionListener lis5 = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String a = t1.getText();
        int n = Integer.parseInt(a);
    } 
};
b1.addActionListener(lis5);

ActionListener lis6 = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int [] tab = new int[n];
        for (int i=0;i<n;i++) {
            tab[i] = in.nextInt();
        }
    } 
};
b2.addActionListener(lis6); 

3 个答案:

答案 0 :(得分:1)

因为n在anonymous interface范围内。

  • 访问封闭范围的本地变量,以及声明和访问匿名类的成员
  •   

    与本地类一样,匿名类可以捕获变量;他们有   对封闭范围的局部变量的相同访问:

         

    匿名类可以访问其封闭类的成员。

         

    匿名类无法访问其封闭的局部变量   未被宣布为最终或有效最终的范围。

         

    与嵌套类一样,是一个类型(如变量)的声明   匿名类会影响封闭中的任何其他声明   具有相同名称的范围。有关详细信息,请参阅阴影。

         

    匿名类也与本地类具有相同的限制   关于他们的成员:

         

    您不能在中声明静态初始化程序或成员接口   匿名课。

         

    匿名类可以提供静态成员   常数变量。

    答案 1 :(得分:1)

    n在第一个actionPerformed的范围内声明。一旦方法结束,它就会“消失”。

    在方法之外声明它

    int n = 0;
    
    ActionListener lis5 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String a = t1.getText();
            n = Integer.parseInt(a)
        } 
    };
    b1.addActionListener(lis5); 
    
    int[] tab;
    
    ActionListener lis6 = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tab = new int[n];
            for(int i = 0 ; i < n ; i++) {
                tab[i] = in.nextInt();
            }
        } 
    };
    b2.addActionListener(lis6);
    

    同样适用于tab数组的减速。

    答案 2 :(得分:0)

    如果您需要能够在一个动作侦听器中更新变量,然后在另一个动作侦听器中使用它,则需要引用可变值类型以在两者之间共享。

    您可以简单地使用int[1],但我更喜欢使用AtomicInteger,因为更清楚的是,只有一个整数值被共享:

    final AtomicInteger n = new AtomicInteger();
    ActionListener lis5 = new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            String a = t1.getText();
            n.set(Integer.parseInt(a));
        } 
    };
    b1.addActionListener(lis5); 
    
    ActionListener lis6 = new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            int nn = n.get();
            int [] tab = new int[nn];
            for(int i=0;i<nn;i++){
                tab[i] = in.nextInt();
            }
        } 
    };
    b2.addActionListener(lis6);