Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ilegal start of type for a for loop?

Tags:

java

Why am I getting the error :java:16: error: illegal start of type for(int i = 0; i < 9; i++){ I have checked old labs and this is the correct usage of it I thought.

import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;


class Lab3Panel extends JPanel{

    Lab3Panel () {

        setLayout(new GridLayout(3,3));
    }


    Lab3Label label[] = new Lab3Label[9];

    for(int i = 0; i < 9; i++){

        label[i] = new Lab3Label();
        add(label[i]);
    }
like image 631
Robert Avatar asked Dec 22 '22 02:12

Robert


2 Answers

The for loop needs to be in a method, a constructor, or at a bare minimum, between a pair of {} brackets. But probably a constructor.

like image 96
Louis Wasserman Avatar answered Jan 08 '23 14:01

Louis Wasserman


Your loop code is perfectly legal, but it needs to be inside a method for it to actually be interpreted as code and run. Currently its just sitting inside the class declaration along with the line before it, so the poor compiler has no idea what you want to do with that code or when you want it to run. :D

like image 27
Gordon Gustafson Avatar answered Jan 08 '23 13:01

Gordon Gustafson