简体   繁体   中英

How do I make an IF statement that compares 2 integers assigned to 2 string variables in 1 class then execute the code in another class in Java?

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;
}

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())

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, ie:

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, ie:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM