注意:请记住,我是 java 和 stackoverflow 的新手,这是我的第一个问题。
好吧,我正在用 java 制作一个基于控制台的基本游戏, 我有一个问题。我有一长串 if else 语句。我怎样才能缩短它们? 我尝试查看 Is there anyway to shorten if else statements instead of going in circles但我没有得到我需要的答案。 这是我的程序中的一些示例代码:
import java.util.Scanner;
public class FishMain {
public static void main(String[] args) {
FishClass myFish = new FishClass();
//Makes a scanner for user input/commands
Scanner userComSc = new Scanner(System.in);
//scans for what the user types
String userCom = userComSc.nextLine();
//checks if the userCommand isn't /end or exit (when it is it will terminate)
while(!userCom.equals("/end") && !userCom.equals("/exit")) {
if(userCom.equals("/dive 1")){
myFish.dive(1);
}
else if(userCom.equals("/dive 2")){
myFish.dive(2);
}
else if(userCom.equals("/dive 3")){
myFish.dive(3);
} else if
//so on till 99...
}
我尝试过这样的事情:
if(userCom.startsWith("/dive")){
int howDeep = Integer.parseInt(userCom);
myFish.dive(howDeep);
}
但最终会出现错误。这是错误消息:
//user types
/dive 6
Exception in thread "main" java.lang.NumberFormatException: For input string: "/dive 6"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at FishMaster.main(FishMaster.java:40)
请帮我找出我做错了什么。
编辑 1:很抱歉“/dive 1”(英尺)使 myFish 潜水 3 英尺,这是一个拼写错误,现已修复...
最佳答案
这是一个好主意,不幸的是,您正在尝试将包含非数字字符的字符串解析为 int。您需要从字符串中提取 Int 子串,如下所示:
if(userCom.startsWith("/dive")){
String str = userCom.subString(6);
int howDeep = Integer.parseInt(str);
myFish.dive(howDeep);
}
关于java - 如何缩短java中的if else语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24789562/