简体   繁体   中英

How to return string and int type in a method?

Write a class for a video game character. The character should have a name, a type (scout, soldier, medic, etc.) and current health. Therefore it needs three attributes:

String name, String type, int health

This class should have the following methods:

GameCharacter( String newName, String newType, newCurHealth ) Constructor that takes three inputs.

changeHealth( int change ) A method that changes the health of the character. The character's health will change by change amount, so it will go down if change is negative, and up if it's positive. If the health goes below 0, changeHealth should return the String "Your character is dead".

Here is my code so far. Is there anything I can do to make it better? & a way to return a string in my second method?

public class GameCharacter {
    private String name;
    private String type;
    private int health;

    public GameCharacter(String newName, String newType, int newCurHealth){
        name = newName;
        type = newType;
        health = newCurHealth;
    }

    public int changeHealth (int change){
        if (change < 0){
            return health - change;
        } else if (change > 0){
            return health + change;
        } else if (health < 1){
            // string that character is dead
        }
    }

    public static void main(String[] args){
        GameCharacter Mario = new GameCharacter ("Mario", "Hero", 100);
        GameCharacter Luigi = new GameCharacter ("Luigi", "Sidekick", 100);
        GameCharacter Bowser = new GameCharacter ("Bowser", "Villian", 100);
    }
}

You cannot return either an int or a String . You have to pick one type and you should re-think your design, if you want to output a message. Eg just check the return value of changeHealth() after calling the method.

Or you could define a custom exception (or use an existing one). Just to get you started:

public int changeHealth(int change) {
  int result = health;

  if (health < 1) {
    throw new IllegalStateException("Cannot change health, character is dead already.");
  }

  // Calculate health change (if any)
  health += change;

  // Return new health
  return health;
}

Humbly, I think what you want isn't a good way. Your methods should be so semantics as possible.

A better approach would be return a negative int and your class GameCharacter can have a method isDead or isAlive that will give you this state.

public class GameCharacter {
    private String name;
    private String type;
    private int health;

    public boolean isAlive(){ return health>0; }
    public boolean isDead(){ !isAlive(); }
}

I think you misunderstood the assignment. The method is not supposed to return the new health, but to change the health of that character, ie just update this.health "in place" and change the returned type to String .

Also, no need to check whether change is positive or negative; just add it to health !

public String changeHealth (int change) {
    this.health += change
    if (health < 1) {
         return "Your character is dead";
    } else {
        return null; // or whatever
    }
}

Edit: While other answers propose some good alternatives and additions to the Character API, given that this looks like an assignment, I think you should stick to the description of the method, ie change the health, and return a string.

It would make more sense to always return the same thing, regardless of whether your character is dead or not.

For example:

public class GameCharacter {
    private String name;
    private String type;
    private int health;


    public GameCharacter(String newName, String newType, int newCurHealth){
        name = newName;
        type = newType;
        health = newCurHealth;
    }

    public String changeHealth (int change){
        // Adding positive number will increase health.
        // Adding negative number will decrease health.
        health += change;
        if (health > 0){
            return "Your character now has " + health + " health.";
        } else {
            return "Your character is dead.";
        }
    }

    public static void main(String[] args){
        GameCharacter Mario = new GameCharacter ("Mario", "Hero", 100);
        GameCharacter Luigi = new GameCharacter ("Luigi", "Sidekick", 100);
        GameCharacter Bowser = new GameCharacter ("Bowser", "Villain", 100);
    }
}

If you declare a method to return an int you cannot make it return a String as a "special result".

There are several ways to solve your problem. You can add a method like checkAlive() which returns true if the current health is greater than 0 and false otherwise, or make the caller check the returned value (which should be the health after the change) and print the string if that value is smaller than or equal to 0.

Also I think you have some bugs in your concept: first, your method doesn't change the health value inside your class; second, the code inside the last if, where you want to return the string, will be executed only when 0 is passed as parameter to the method. That's probably not what you want. To follow my suggestion edit the method like this:

public int changeHealth(int change) {
    health += change;
    return health;
}
public String changeHealth(int change) {
    health += change;
    return health < 0 ? "Your character is dead" : null;
}

Few things,

first, dont worry, your character will never die

  if (change < 0){
         return health - change;
     } else if (change > 0){
         return health + change;
     }

you are adding positive change value to health and substracting negative value from it. Mathematics 101 x - (-y) == x+y

second, your character might dead, but i dont think any action related to him being dead should be happened inside `GameCharacter' class. i suggest you to return true/false value which indicate is character still alive. or create enum. if you go that way, you culd have multiple states (alive, almost_dead, dead)

I would rethink the design, particularly around the changeHealth method. However, if you really want to have a combined return type of an int and an optional string, you could create a new class, say, HealthStatus , that actually contains an Optional<String> :

public class HealthStatus {
    public final int health;
    public final Optional<String> message;

    public HealthStatus(int health, String message) {
        this.health = health;
        this.message = Optional.of(message);
    }

    public HealthStatus(int health) {
        this.health = health;
        this.message = Optional.empty();
    }

    public int getHealth() {
        return health;
    }

    public Optional<String> getMessage() {
        return message;
    }
}

Then, in your changeHealth method, you can optionally return a message:

public HealthStatus changeHealth(int change) {
    health += change;
    if (health < 1) {
        return new HealthStatus(health, "Your character is dead");
    } else {
        return new HealthStatus(health);
    }
}

And at the point where you call it, you can print the message, if there is one (or do whatever else is appropriate with it):

// take 7 points of damage:
HealthStatus status = changeHealth(-7);
hitPoints = status.getHealth();
// print the message, if there is one
status.getMessage().ifPresent(System.out::println);

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