Reputation: 1663
Why am I getting " } " error in switch statment below. I don't see any syntax error. I don't get error on compiling the code. Eclipse is indicating error at the specified position below.
After putting } I get this error
- The static field KeyEvent.VK_XXXX should be accessed in a
static way
- case expressions must be constant expressions
switch(event.getKeyCode())
{
case event.VK_BACK_SLASH:
backColor=but[27].getBackground();
break;
case event.VK_RIGHT:
for(int i=0;i<but.length;i++)
{
if(" > ".equals(but[i].getText()))
{
backColor=but[i].getBackground();
break;
}
}
break; // error here
}
When I press the key, I get the follwoing error
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete SwitchBlock
at Keyboard$HandlerClass.keyPressed(Keyboard.java:242) // this is break statement
at java.awt.Component.processKeyEvent(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
Regards
Upvotes: 1
Views: 437
Reputation: 11
To solve any compile issues:
Firstly use the class name to refer static content instead of the object reference. Meaning, in the case statements use KeyEvent.VK_BACK_SLASH instead of event.VK_BACK_SLASH
If that does not work out, I suspect there is an error in some other part of your program may be you are not having the right number of matching braces. A simple grep should help you identify the problem. Try grep "{" | wc -l AND grep "}" | wc -l.
To root cause your run-time problem:
Try running it outside the scope of eclipse. Either by adding the root directory to the class path or packaging the class files into a jar file.
Upvotes: 1
Reputation: 54456
The error The static field KeyEvent.VK_XXXX should be accessed in a static way
means what it says: you should access the fields statically, like so:
case KeyEvent.VK_BACK_SLASH:
// Do something
break;
case KeyEvent.VK_RIGHT:
// Do something else
break;
Upvotes: 0
Reputation: 51030
The only problem I could see in your code is the following (but it's not a compiletime/runtime error), which most probably would end up as a bug:
but[i].getText() == " > " //this is called object identity check
That's not the right way to compare strings. Use .equals
method instead
" > ".equals(but[i].getText()) //this is object equality check
Update
The static field KeyEvent.VK_XXXX should be accessed in a static way
That means you should change event.VK_BACK_SLASH
to KeyEvent.VK_BACK_SLASH
, ...
Upvotes: 1