Reputation: 74
I have these 2 string variables, Hulk
and Thing
, Hulk
has a strength of 10
and Thing
has a strength of 53
, they both fight (the IF statement) where the higher integer strength wins.
Then Hulk received a powerup boosting his strength to 110, now both fight again. The winner's name is printed on the screen both times.
I have 2 classes (a main class
and a supporting one
). The IF statement of my supporting class is attached along with my getStrength()
method (if anymore code is needed let me know).
I am getting an error
where is says: if (name1.getStrength() > name2.getStrength()) ;
the error is that getStrength()
isn't defined for string where name1
and name2
are.
Also, after solving this, how do I call this subroutine
in my main class
?
Thanks in advance!
IF Statement:
if (name1.getStrength() > name2.getStrength())
{
System.out.println(name1 + " Wins!");
}
else {
System.out.println(name2 + " Wins!");
}
getStrength method:
int getStrength() {
return this.strength;
}
Upvotes: 2
Views: 112
Reputation: 3140
Firstly you should read about java first steps. But in your app, you should create class which is representing your fighters and in this class create methods which get the strength from it, i.e.:
public class Fighter {
private String name;
private int strenght;
public int getStrength() {
return strength;
}
}
of course you need to create constructor or other setters/getters in this class. Then you can create objects, i.e.:
Fighter hulk = new Fighter();
Fighter thing = new Fighter();
// use constructor or setters to set strength and name
Now you can call method from class Fighter:
if(hulk.getStrength() > thing.getStrength()) {
// your code
}
Your error is because you were trying to call getStrength()
method on object of String
type. The best way is to create your own type.
Upvotes: 1
Reputation: 3429
You need to make the characters as objects of class that has properties like name, strength, etc.
Then this thing should work : if (Hulk.getStrength() > Thing.getStrength())
Upvotes: 2