Your Own droid (Java)


#1

public class Droid {
   
         int batteryLevel;
  
   public Droid(){
        public int batteryLevel = 100;
  
   }
      public void activate(){
      System.out.println("Activated. How can I help you?");
      batteryLevel = batteryLevel - 5;
      System.out.println("Battery level is: " + batteryLevel + "percent.");
   }
       public void chargeBattery(int hours){
       System.out.println("Droid charging....");  
       batteryLevel = batteryLevel + hours;
       if (batteryLevel > 100){
          System.out.println("Overcharging...");
       }
       else{
          System.out.println(batteryLevel);       
       }
  }
       public int checkBatteryLevel(){
            System.out.print("Battery level is: " + batteryLevel);
            return batteryLevel;
    }
       public void hover(int feet){
        if(feet > 2){
             System.out.println("Error! I cannot hover  above 2 feet!");
        }
         else{
            System.out.println("hovering");
             batteryLevel = batterLevel - 20;
           System.out.println("Battery level is: " +       batteryLevel);
         }
       }
       public static void main(String[] args){
           Droid myDroid = new Droid();
           myDroid.activate();
           myDroid.chargeBattery(5);
           myDroid.feet(1);
         
       }
  
}

console tells me

Droid.java:6: error: illegal start of expression
public int batteryLevel = 100;
^
1 error

could anyone helps me with this . thx.


#2

You can't declare public fields in the constructor.
You can create local variables, or you can set fields that have been declared in the class.

You've already declared the field batteryLevel (and shouldn't it be private?)
How do you access that from the constructor?


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.