So here is my Superhero
class:
public class Superhero {
public int strength;
public int powerUp;
public int defaultStrength = 10;
public String name;
public Superhero(String name) {
this.strength = 10;
System.out.println("The Superheroes available are :" + name);
}
public Superhero(String name, int strength) {
if (strength >= 0) {
this.strength = strength;
System.out.println("The Superheroes available are :" + name);
} else {
System.out.println("Error. Strength cannot be < 0");
}
}
public void setStrength( int strength ) {
this.strength = strength;
}
public int getStrength() {
return strength;
}
public void powerUp(int powerUp) {
this.strength += powerUp;
}
}
Here is my Fight
class the problem here is when I run it I get back that the winner result is null
and I don't understand why it is doing that.
import java.io.*;
public class Fight {
public static void main (String args[]) {
Superhero gambit = new Superhero( "Gambit" );
Superhero groot = new Superhero( "Groot", 79);
System.out.println( "Gambit's strength is: " + gambit.strength);
System.out.println( "Groot's strength is: " + groot.strength);
System.out.println("The winner of the fight is: " + fight(gambit, groot));
}
static String fight(Superhero a, Superhero b)
{
if (a.strength > b.strength)
{
return a.name;
} else
{
return b.name;
}
}
}
Look at your constructor:
public Superhero(String name) {
this.strength = 10;
System.out.println("The Superheroes available are :" + name);
}
That sets the instance field strength
, but doesn't do anything with the name
instance field. Your other constructor is the same. You need to include:
this.name = name;
to copy the value from the parameter into the instance variable. Do this in both constructors. Otherwise you just end up with the default value for name
, which is a null reference.
As an aside, I'd strongly recommend making your fields private and adding a getName()
method to retrieve the name from else your fight
method. I'd also throw an exception instead of just printing out an error message if the strength is below 0, and also I'd make the constructor which doesn't take a strength
parameter just chain to the one that does:
public Superhero(String name) {
this(name, 10);
}
public Superhero(String name, int strength) {
if (strength < 0) {
throw new IllegalArgumentException("strength cannot be negative");
}
this.strength = strength;
this.name = name;
System.out.println("The Superheroes available are :" + name);
}
(The message displayed by the constructor is a bit odd, given that it's only listing a single name, but that's a different matter.)
See more on this question at Stackoverflow