Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 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 Answer

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++) {
          ...
        }
    }
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...