注意:请记住,在java和stackoverflow上我都是新手,这是我的第一个问题。
好的,所以我用Java开发了一个基于控制台的基本游戏,但遇到了问题。我有一长串if else语句。如何缩短它们?我曾尝试查看是否有其他方法来缩短if语句,而不是圈个圈,但是我没有得到所需的答案。这是我程序中的一些示例代码:
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:很抱歉让myFish下潜3英尺的“ / dive 1”(英尺)感到困惑,这是一个错字,现在已修复...
不幸的是,这是一个好主意,您正在尝试将非数字字符的字符串解析为int。您需要从字符串中将Int子字符串化,如下所示:
if(userCom.startsWith("/dive")){
String str = userCom.subString(6);
int howDeep = Integer.parseInt(str);
myFish.dive(howDeep);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句