2014-10-19 45 views
-1
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;只允许抽象或最终”。这应该是什么解决方案?我对java很新。获取下面列出的错误消息

+0

把'Stoplight'并在'main'方法外声明 - 然后,你可以通过'Stoplight sl = new Stoplight );'从'main'方法内部 – ochi 2014-10-19 07:12:52

+0

完成但仍然出错“它给出了一个错误,”公共类型的Stoplight必须在它自己的文件中定义“ – 2014-10-19 07:56:25

回答

0

Stoplight类定义移到主要方法之外。

2

的问题是,你有不当试图将类声明Stoplight的方法(你main法)。

这在技术上是允许的(是的,它是!这是一个本地类),但如果你在这种情况下声明一个类,你不能将它声明为public。 (想想看,类的声明是直观地只在方法体范围内,所以它声明为public是没有意义的。)

说了这么多,这是可能这里就不做正确的事。更好的解决方案是将Stoplight类移入单独的文件,或者将其移入(可名为)的TrrfcLgt类中,以使其成为嵌套类。 (如果你使用后者,将它改为static ...)

+0

在你遵循你所说的话之后。它给出了一个错误“公共类型的Stoplight必须在它自己的文件中定义” – 2014-10-19 07:54:03

+0

你把它放在错误的地方,要么把类放在一个单独的文件中(最好的想法),要么把它放在** TrffcLgt上课......就像我上面说的 – 2014-10-19 08:01:51

+0

谢谢史蒂芬:) – 2014-10-19 08:18:13