简体   繁体   English

如何在方法中返回字符串和int类型?

[英]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. GameCharacter( String newName, String newType, newCurHealth )构造函数,需要三个输入。

changeHealth( int change ) A method that changes the health of the character. changeHealth( int change )更改角色健康状况的方法。 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". 如果运行状况低于0,则changeHealth应该返回字符串“您的字符已死”。

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 . 您不能返回intString 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. 例如,只需在调用方法后检查changeHealth()的返回值changeHealth()

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. 更好的方法是返回一个负数int,并且您的类GameCharacter可以具有isDead或isAlive方法,它将为您提供此状态。

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 . 该方法不应返回新的健康状况,而应更改该字符的健康状况,即仅“就地”更新this.health并将返回的类型更改为String

Also, no need to check whether change is positive or negative; 同样,无需检查change是正面还是负面。 just add it to health ! 只需将其添加到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. 编辑:虽然其他答案为Character API提出了一些很好的替代方案和补充,但鉴于这看起来像是一个赋值,我认为您应该坚持对方法的描述,即更改运行状况并返回字符串。

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". 如果声明返回int的方法,则不能使其返回字符串作为“特殊结果”。

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. 您可以添加类似checkAlive()的方法,如果当前健康状况大于0,则返回true;否则返回false;或者使调用方检查返回的值(更改后的健康状况),并在返回值时显示字符串小于或等于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. 其次,只有在将0作为参数传递给方法时,才会执行最后一个if(要在其中返回字符串)的代码。 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 数学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. 第二,你的角色可能死了,但是我不认为与他死有关的任何动作都应该在“ GameCharacter”类中发生。 i suggest you to return true/false value which indicate is character still alive. 我建议您返回true / false值,以指示字符仍然有效。 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. 我会重新考虑设计,尤其是围绕changeHealth方法。 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> : 但是,如果您确实希望将int和可选字符串的返回类型组合在一起,则可以创建一个新类,例如HealthStatus ,该类实际上包含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: 然后,在您的changeHealth方法中,可以选择返回一条消息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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