我是java的新手。获取下面列出的错误消息

时间:2014-10-19 07:08:12

标签: java

package StreetKing;

import java.awt.Color;

public class TrffcLgt {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /**
        * This class represents a simple implementation of a stoplight.
        * The client can determine the current state of the stoplight by
        * calling stoplight.getState() and change it to the next color
        * in the sequence (GREEN -> YELLOW -> RED -> GREEN) by calling
        * stoplight.advance().
        */
        public class Stoplight {
        /** Constant indicating the color GREEN */
        public static final Color GREEN = Color.GREEN;
        /** Constant indicating the color YELLOW */
        public static final Color YELLOW = Color.YELLOW;
        /** Constant indicating the color RED */
        public static final Color RED = Color.RED;
        /**
        * Creates a new Stoplight object, which is initially GREEN.
        */
        public Stoplight() {
            state = 0;
        }

        /**
        * Returns the current state of the stoplight.
        * @return The state of the stoplight (GREEN, YELLOW, or RED)
        */
        public Color getState() {
            switch (state) {
                case 0: return GREEN;
                case 1: return YELLOW;
                case 2: return RED;
                default: return null; /* Can't occur but required by Java */
             }
        }

        /**
        * Advances the stoplight to the next state.
        */
        public void advance() {
            state = (state + 1) % 3;
        }

        /* Private instance variable */
        private int state;
        }
    }

}

获取错误消息"本地类Stoplight的非法修饰符;只允许抽象或最终#34;应该解决这个问题的方法是什么?

2 个答案:

答案 0 :(得分:2)

问题在于您不恰当地尝试在方法中声明类Stoplight (您的main方法)。

这在技术上是允许的(是的!它是本地类)但是如果在此上下文中声明了一个类,则不能将其声明为public。 (考虑一下。类声明直观地仅在方法体内的范围内。因此将其声明为public毫无意义。)

话虽如此,可能在这里做的不是正确的事。更好的解决方案是将Stoplight类移动到单独的文件中,或将其移动到(名义上命名的)TrrfcLgt类中,以便它是嵌套类。 (如果您执行后者,请将其更改为static ...)

答案 1 :(得分:0)

Stoplight类定义移到main方法之外。