Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

java - for loop gets error "illegal start of type"

so im trying to create a program in java which will create a 10 by 10 matrix, with each element displaying either a 1 or a 0 randomly. Here is what i have so far:

package random.matrix;

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

class ex2 extends JFrame {

    class Random {
        GridLayout setLayout= new GridLayout(10, 10);

        for (int i = 0; i < 10; i++) {
            int number = (int) (Math.random() * 2);
            String str = Integer.toString(number);
            add(new JLabel(str, JLabel.CENTER));
        }
    }

    public static void main(String[] args) {
        JFrame frame = new ex2();
        frame.setTitle("RandomMatrix");
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

As far as I can tell, this program should run perfectly. However, every time I try, it says something along the lines of "illegal start of type," referring specifically to the for loop line. Can anyone help me troubleshoot this? I've never encountered an error quite like this one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to place your code in a code block such as a method or constructor rather than the class block of an inner class

/**
 * TODO: Refactor later NOT to extend from JFrame
 */
class MyFrame extends JFrame {

    void initComponents() {
        GridLayout setLayout = new GridLayout(10, 10);

        for (int i = 0; i < 10; i++) {
          ...
        }
    }
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...