Stupid Java question, why isnt switch working outside of the main method?

Sharky Forums


Results 1 to 5 of 5

Thread: Stupid Java question, why isnt switch working outside of the main method?

  1. #1
    Mako Shark Mancora's Avatar
    Join Date
    Jun 2001
    Location
    The other side of where the fishes swim
    Posts
    4,313

    Stupid Java question, why isnt switch working outside of the main method?

    ok, after i cut out all of the inside stuff heres where im getting the error



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


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

    Code:
    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.


    Code:
    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

  2. #2
    Hammerhead Shark
    Join Date
    Feb 2001
    Location
    Columbus, Ohio
    Posts
    1,277
    You class file doesn't have a constructor or method or anything. You class files have to have some sort of method.

  3. #3
    Hammerhead Shark EverlastingGod's Avatar
    Join Date
    Feb 2003
    Location
    MD
    Posts
    1,364
    Originally posted by anfpunk
    You class files have to have some sort of method.
    No, they don't.
    Code:
    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.
    Stay cool
    and be somebody's fool this year

  4. #4
    Hammerhead Shark
    Join Date
    Feb 2001
    Location
    Columbus, Ohio
    Posts
    1,277
    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.

  5. #5
    Mako Shark Mancora's Avatar
    Join Date
    Jun 2001
    Location
    The other side of where the fishes swim
    Posts
    4,313
    thanks

    <--- the dangers of taking first java class last fall, not practicing it for a year, and expecting to be perfect.
    Last edited by Mancora; 09-22-2003 at 12:26 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •