getting illegal start of expression error

前端 未结 2 1531
傲寒
傲寒 2021-01-16 20:37

i\'m totally new to java. i \'m try to create my first program & i get this error.

E:\\java>javac Robot.java
Robot.java:16: error: illegal start of ex         


        
2条回答
  •  伪装坚强ぢ
    2021-01-16 21:05

    You're trying to define a method (CreateNew) within a method (main), which you cannot do in Java. Move it out of the main; and as model and status appear to be instance variables (not method variables), move them as well:

    public class Robot {
        // Member variables
        String model;
        /*int year;*/
        String status;
    
        // main method
        public static void main(String args[]){
    
            // Presumably more stuff here
        }
    
        // Further method    
        public String CreateNew () {
            Robot optimus;
            optimus = new Robot();
            optimus.model="Autobot"; 
            /*optimus.year="2008";*/
            optimus.status="active";
            return (optimus.model);
        }
    }
    

    Based on its content, you may want CreateNew to be static (so it can be called via Robot.CreateNew rather than via a Robot instance). Like this:

    public class Robot {
        // Member variables
        String model;
        /*int year;*/
        String status;
    
        // main method
        public static void main(String args[]){
    
            // Presumably more stuff here
        }
    
        // Further method    
        public static String CreateNew () {
        //     ^----------------------------- here's the change
            Robot optimus;
            optimus = new Robot();
            optimus.model="Autobot"; 
            /*optimus.year="2008";*/
            optimus.status="active";
            return (optimus.model);
        }
    }
    

    Used as

    String theModel = Robot.CreateNew();
    

    ...although it's unclear to me why you want to create a Robot instance and then throw it away and just return the model instance member's value.


    Somewhat off-topic, but the overwhelming convention in Java is that method names (static or instance) start with a lower-case letter, e.g. createNew rather than CreateNew.

提交回复
热议问题