for loop gets error “illegal start of type”

后端 未结 2 1728
一整个雨季
一整个雨季 2021-01-24 08:22

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:



        
相关标签:
2条回答
  • 2021-01-24 09:01

    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++) {
              ...
            }
        }
        ...
    }
    
    0 讨论(0)
  • 2021-01-24 09:01

    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.

    0 讨论(0)
提交回复
热议问题