Build a Droid - Missing Return Statement

Hi,

This is my code.

public class Droid{
String name;
int batteryLevel;

//toString Method
public String toString(){
return "This droid’s name is " + name;
}

//Perfom Task Method
public String performTask(String task){
System.out.println(name + "is performing task: " + task + “.”);
batteryLevel= batteryLevel - 10;
System.out.println(batteryLevel);
}

//Contructor Method
public Droid(String droidName){
name = droidName;
batteryLevel = 100;
}
//Main Method - do my stuff here.
public static void main(String args){
Droid codey = new Droid(“Codey”); // Set 1st instance.
System.out.println(codey);
codey.performTask(“dancing”);
codey.performTask(“Interfacing with the Falcon!”);
codey.performTask(“Fixing Hyperdrive!”);

}
}

And this is the error I cannot figure out.

Output:
Droid.java:15: error: missing return statement
}
^
1 error

Thanks for your time and help in advance.

The performTask method has a return type String but it does not return a String at the end.

You could put
return name + "is performing task: " + task + ".";
at the end of the method.

2 Likes

Ok, that was one bug. Thank you.

Though this snippet now returns a String when calling the method it doesn’t actually print anything.

//Perform Task Method

public String performTask(String task){

return name + "is performing task: " + task + “.”;

}

The output of the program is just this.
This droid’s name is Codey
This droid’s name is R2D2

Once again, here is the complete code.

public class Droid{
String name;
int batteryLevel;

//toString Method
public String toString(){
return "This droid’s name is " + name;
}

//Battery Level Method
public void batteryLevel(){
batteryLevel = batteryLevel - 10;
}

//Perfom Task Method
public String performTask(String task){
return name + "is performing task: " + task + “.”;
}

//Contructor Method
public Droid(String droidName){
name = droidName; // Set the name of the Droid instance.
batteryLevel = 100; // Set initial Battery Level.
}
//Main Method - do my stuff here.
public static void main(String args){
Droid codey = new Droid(“Codey”); // Set 1st instance.
Droid R2D2 = new Droid(“R2D2”); // Set 1st instance.
System.out.println(codey);
System.out.println(R2D2);
codey.performTask(“dancing”);
R2D2.performTask(“Toss lightsaber”);

}
}

you could put stuff in the method and then return a string afterward.

public String performTask(String task){
  System.out.println(name + "is performing task: " + task + ".");
  batteryLevel= batteryLevel - 10;
  System.out.println(batteryLevel);
  return name + "is performing task: " + task + ".";
}

or you could change the return type to void if you don’t want it to return anything.

1 Like