Click to See Complete Forum and Search --> : Stupid Java question, why isnt switch working outside of the main method?


Mancora
09-20-2003, 09:55 PM
ok, after i cut out all of the inside stuff heres where im getting the error




class Switchtest {
switch(5) {
default:
System.out.println("p");
}
}




That should be valid right? Well heres the error im getting


d:\prog\java>javac switch.java
switch.java:4: illegal start of type
switch(5) {
^
switch.java:7: <identifier> expected
}
^
2 errors

d:\prog\java>



The second error is due to the first one, since its not recongizing switch, though WHY? When i add in the main method it compiles just fine.



class Switchtest {
public static void main(String[] args) {
switch(5) {
default:
System.out.println("p");
}
}
}



I should be using the 1.4.2 Java SDK

anfpunk
09-21-2003, 02:05 PM
You class file doesn't have a constructor or method or anything. You class files have to have some sort of method.

EverlastingGod
09-22-2003, 12:44 AM
Originally posted by anfpunk
You class files have to have some sort of method.

No, they don't.
class MyClass
{
}
is valid.

However, the point I think you're trying to make is correct... the switch statement must be in a constructor, method or static initializer.

anfpunk
09-22-2003, 10:10 AM
You are very correct. That is a common way of satisfying classes and methods that haven't been written yet. I need to be more careful is how I say things.

Mancora
09-22-2003, 11:44 AM
thanks :)

<--- the dangers of taking first java class last fall, not practicing it for a year, and expecting to be perfect.