Java For循环问题

时间:2013-12-20 15:45:43

标签: java loops for-loop cycle

JButton nupp0 = new JButton(); // Teen nupu objektid, rida 54 
JButton nupp1 = new JButton();
JButton nupp2 = new JButton();
JButton nupp3 = new JButton();
JButton nupp4 = new JButton();
JButton nupp5 = new JButton();
JButton nupp6 = new JButton();
JButton nupp7 = new JButton();

public JButton nupud[] = { nupp0, nupp1, nupp2, nupp3, nupp4, nupp5, nupp6, nupp7 };

我被告知要在for循环中创建这段代码,我尝试了很多方法,但我无法让它工作。任何想法?

这是我的两次尝试:

for (int i =0 ; i < nupud.length ; i++) {
    JButton nupud[i] = new JButton;     
}

for (int i = 0 ; i < nupud.length ; i++) {
    nupud[i] = new JButton();
}

3 个答案:

答案 0 :(得分:5)

首先新建数组:

JButton[] nupud = new JButton[8];
for (int i = 0 ; i < nupud.length; i++){
    nupud[i] = new JButton();
}

答案 1 :(得分:0)

在for循环之前看起来你错过了这个。

JButton[] nupud = new JButton[length];

答案 2 :(得分:0)

我只是检查它的日食工作:

package com.demo.swain;

public class JButton {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JButton nupp0 = new JButton(); // Teen nupu objektid, rida 54 
        JButton nupp1 = new JButton();
        JButton nupp2 = new JButton();
        JButton nupp3 = new JButton();
        JButton nupp4 = new JButton();
        JButton nupp5 = new JButton();
        JButton nupp6 = new JButton();
        JButton nupp7 = new JButton();

     JButton[] nupud = { nupp0, nupp1, nupp2, nupp3, nupp4, nupp5, nupp6, nupp7};
        for (int i =0 ; i < nupud.length ; i++) {
            nupud[i] = new JButton();
                  System.out.println(nupud[i]);
        }
    }

}

输出:

com.demo.swain.JButton@dc74f8d
com.demo.swain.JButton@1837b90c
com.demo.swain.JButton@7255cf3f
com.demo.swain.JButton@5f996bbd
com.demo.swain.JButton@51707653