java 如何在方法中返回字符串和整数类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28946291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return string and int type in a method?
提问by Zafar
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".
为视频游戏角色编写一个类。角色应该有名字、类型(侦察兵、士兵、军医等)和当前的健康状况。因此它需要三个属性:
String name, String type, int health
这个类应该有以下方法:
GameCharacter( String newName, String newType, newCurHealth )
接受三个输入的构造函数。
changeHealth( int change )
一种改变角色健康的方法。角色的生命值会随着变化量而变化,所以如果变化是负值,它会下降,如果是正值,它会上升。如果生命值低于 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);
}
}
回答by user1438038
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. E.g. just check the return value of changeHealth()
after calling the method.
您不能返回 anint
或 a String
。如果您想输出消息,您必须选择一种类型,并且应该重新考虑您的设计。例如,只需检查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;
}
回答by Kaitlin Hipkin
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);
}
}
回答by Antiphon0x
If you declare a method to return an int you cannot make it return a String as a "special result".
如果你声明一个方法来返回一个 int 你不能让它返回一个 String 作为“特殊结果”。
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. That's probably not what you want. To follow my suggestion edit the method like this:
另外我认为你的概念有一些错误:首先,你的方法不会改变你班级内的健康值;其次,最后一个 if 中的代码,您要返回字符串的位置,只有在将 0 作为参数传递给方法时才会执行。那可能不是您想要的。要按照我的建议编辑方法,如下所示:
public int changeHealth(int change) {
health += change;
return health;
}
回答by Danilo Gomes
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.
更好的方法是返回一个负整数,并且您的类 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(); }
}
回答by tobias_k
I think you misunderstood the assignment. The method is not supposed to returnthe new health, but to changethe health of that character, i.e. 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; just add it to health
!
此外,无需检查change
是正还是负;只需将其添加到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, i.e. changethe health, and returna string.
编辑:虽然其他答案对Character
API提出了一些很好的替代方案和补充,但鉴于这看起来像是一项分配,我认为您应该坚持方法的描述,即更改健康状况,并返回一个字符串。
回答by Andrey
public String changeHealth(int change) {
health += change;
return health < 0 ? "Your character is dead" : null;
}
回答by user902383
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. 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)
其次,你的角色可能会死,但我认为任何与他死有关的动作都不应该发生在`GameCharacter' 类中。我建议你返回真/假值,这表明角色还活着。或创建枚举。如果你那样做,你就会有多个状态(活着,几乎死了,死了)
回答by David Conrad
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>
:
我会重新考虑设计,特别是围绕changeHealth
方法。但是,如果您真的想要组合返回类型 anint
和一个可选字符串,您可以创建一个新类,例如,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);