gpt4 book ai didi

Java:从方法返回字符串

转载 作者:行者123 更新时间:2023-11-30 07:36:41 24 4
gpt4 key购买 nike

我想指出,我对 Java 还很陌生,这就是为什么我可能会犯一些愚蠢的错误。

我有一个名为“Characters”的类,它由 4 个变量和多个方法组成。所有变量都是私有(private)的,因此根据我所读到的内容,我需要使用方法对它们执行任何操作。

其中一种方法应该以字符串形式返回变量之一,但是我不断从 Eclipse 和运行它时收到错误。 “此方法必须返回“String”类型的结果。错误发生在该方法的第一行:

public String displayStats(String option) {
switch (option) {
case "charName":
System.out.println(charName);
return charName;
case "charHealth":
System.out.println(charHealth);
String charHealth2 = Integer.toString(charHealth);
return charHealth2;
case "charMana":
System.out.println(charMana);
String charMana2 = Integer.toString(charMana);
return charMana2;
case "charStamina":
System.out.println(charStamina);
String charStamina2 = Integer.toString(charStamina);
return charStamina2;
default:
System.out.println("Error on default");}
}

}

全类:

package basics;

public class Characters {

private String charName = "";
private int charHealth = 0;
private int charMana = 0;
private int charStamina = 0;

public void summoner(Characters player) {
player.charName = "Summoner";
player.charHealth = 80;
player.charMana = 150;
player.charStamina = 50;}

public void sentinel(Characters player) {
player.charName = "Sentinel";
player.charHealth = 200;
player.charMana = 50;
player.charStamina = 100;}

public void beserker(Characters player) {
player.charName = "Beserker";
player.charHealth = 100;
player.charMana = 0;
player.charStamina = 200;}

public void mage(Characters player) {
player.charName = "Mage";
player.charHealth = 80;
player.charMana = 200;
player.charStamina = 20;}

public String displayStats(String option) {
switch (option) {
case "charName":
System.out.println(charName);
return charName;
case "charHealth":
System.out.println(charHealth);
String charHealth2 = Integer.toString(charHealth);
return charHealth2;
case "charMana":
System.out.println(charMana);
String charMana2 = Integer.toString(charMana);
return charMana2;
case "charStamina":
System.out.println(charStamina);
String charStamina2 = Integer.toString(charStamina);
return charStamina2;
default:
System.out.println("Error on default");}
}

}

最佳答案

在 switch 语句的默认情况下,您不会返回任何内容,这意味着该方法有可能(无论多么小)不知道要返回什么。

关于Java:从方法返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35299095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com