【问题标题】:for loop gets error "illegal start of type"for 循环得到错误“类型的非法开始”
【发布时间】:2014-02-11 01:53:11
【问题描述】:

所以我试图在 java 中创建一个程序,该程序将创建一个 10 x 10 矩阵,每个元素随机显示 1 或 0。这是我目前所拥有的:

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);
    }
}

据我所知,这个程序应该可以完美运行。但是,每次我尝试时,它都会说一些类似于“非法开始类型”的内容,具体指的是 for 循环行。谁能帮我解决这个问题?我从来没有遇到过像这样的错误。

【问题讨论】:

标签: java loops for-loop


【解决方案1】:

你需要将你的代码放在一个代码块中,比如方法或构造函数,而不是内部类的类块中

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

【讨论】:

    【解决方案2】:

    类定义中不能有任意语句。也许你想把它放在构造函数中?

    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));
            }
        }
    }
    

    或者,您可以创建另一个方法并将其放入其中。

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2017-11-18
      • 2022-06-11
      • 2013-12-04
      • 2013-10-28
      相关资源
      最近更新 更多