java - 如何缩短java中的if else语句?

标签 java if-statement

注意:请记住,我是 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/

相关文章:

Java:如果用户输入 'y' | |'Y' 测验开始 ,'n' | |'N' 测验结束,休息时显示无效。我想当用户输入以 y 或 n 开头的单词时显示无效

c 如何检查数组的第一个字符

java - JPA 多对多

java - GWT 和 web.xml

java - Jboss 7 - 线程仅在 60 秒后释放

java - 寻找一个轻量级的 java 兼容内存键值存储

java - 在 JavaFX 中单击可编辑 TableView 单元格外部时如何提交?

java - Java中使用compareTo进行排序

java - 检查线程是否为 null 的方法(在 Java 中),操作数位置是否有所不同

c# - 在if语句中,如果其中一个由or分隔的部分返回true,是否继续语句?