Philip R.
Philip R.

Reputation: 345

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.

Upvotes: 2

Views: 15505

Answers (2)

Reimeus
Reimeus

Reputation: 159754

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

Upvotes: 9

tckmn
tckmn

Reputation: 59273

You can't have arbitrary statements inside a class definition. Perhaps you want to put it in the constructor?

class Random {
    public 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);
           setLayout.add(new JLabel(str, JLabel.CENTER));
        }
    }
}

Or, you could just create another method and place it in there.

Upvotes: 1

Related Questions