Hey guys,
I have a question regarding part of this exercise:
https://www.codecademy.com/courses/learn-java/projects/build-a-droid
I got everything working up to the last part of step 13. I’ll post my whole code for this exercise below but my problem is specifically with this section:
public void energyTransfer(String droidName,int amountToTransfer){
this.batteryLevel = this.batteryLevel - amountToTransfer;
droidName.batteryLevel = droidName.batteryLevel + amountToTransfer;
System.out.println("Transferred "+amountToTransfer+"% energy from "+this.droidName+" to "+droidName);
System.out.println(this.droidName+"'s energy level is now at "+this.batteryLevel+"%.");
System.out.println(droidName+"'s energy level is now at "+droidName.batteryLevel+"%.");
}
Not sure if what I’m trying to do is going completely into the wrong direction so feel free to throw this whole section overboard. What I tried to do is this: I want to reference the instance field droidName as a parameter for this method so that
droidName.batteryLevel
becomes
my2ndDroid.batteryLevel
when you call
myDroid.energyTransfer(my2ndDroid, 5);
I would be very grateful for any helpful tips or comments. I only started with Java two days ago and I realize that I may have “painted myself into a corner” on this one
Complete code for this exercise:
public class Droid{
public String droidName;
public int batteryLevel;
// Droid constructor
public Droid(String name){
batteryLevel = 100;
droidName = name;
System.out.println("- - - - -");
System.out.println("Creating new Droid...");
System.out.println("- - - - -");
System.out.println("Hi! I'm a Droid and my name is " + droidName + "! My current battery levels are at "+batteryLevel+"%!");
}
public String toString(){
return "Hi! I'm a Droid and my name is " + droidName + "! My current battery levels are at "+batteryLevel+"%!";
}
public void performTask(String task){
System.out.println(droidName + " is performing the task: " + task);
batteryLevel = batteryLevel - 10;
this.energyReport();
}
public void energyReport(){
System.out.println(droidName+"'s current battery level is at "+ batteryLevel+"%!");
}
public void energyTransfer(String droidName,int amountToTransfer){
this.batteryLevel = this.batteryLevel - amountToTransfer;
System.out.println("Transferred "+amountToTransfer+"% energy from "+this.droidName+" to "+droidName);
System.out.println(this.droidName+"'s energy level is now at "+this.batteryLevel+"%.");
System.out.println(droidName+"'s energy level is now at "+"%.");
}
public static void main(String[] args){
Droid myDroid = new Droid("Codey");
myDroid.performTask("cleaning");
myDroid.performTask("cooking");
myDroid.performTask("washing the dishes");
Droid my2ndDroid = new Droid("Andrew");
my2ndDroid.performTask("dusting");
myDroid.performTask("bitching");
myDroid.energyTransfer(my2ndDroid.droidName, 5);
}
}