繁体   English   中英

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

[英]How to shorten an if else statement in java?

注意:请记住,我是java和stackoverflow的新手,这是我的第一个问题。

好吧,所以我在java中制作一个基于控制台的基本游戏,我遇到了问题。 我有一长串if else语句。 我怎么能缩短它们? 我试过看是否有任何方式缩短if else语句而不是圈内但我没有得到我需要的答案。 这是我的程序中的一些示例代码:

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 7开始, switch语句支持String常量,因此您的代码可以变为:

switch (userCom) {
    case "/dive 1":
        //...
        break;
    case "/dive 2":
        //...
        break;
    case "/dive 3":
        //...
        break;
    //and on...
}

更好的方法是将数据存储在Map<String, Object>以便使用userCom作为关键字来搜索特定数据:

Map<String, Object> data = new HashMap<String, Object>();
data.put("/dive 1", ...);
data.put("/dive 2", ...);
data.put("/dive 3", ...);
//...
myFish.dive(data.get(userCom));

如果您的唯一命令是/ dive $ {arg} ,那么在解析语句之前删除* / dive *会更好:

String singleArgument = userCom.substring(userCom.indexOf(' '));
//singleArgument value is the number after */dive *

请注意, 只有当您的对象在/ dive之后收到参数的特定值时,上述方法才有效 我注意到这一点,因为您已在代码示例中说明:

if(userCom.equals("/dive 1")){
    myFish.dive(3); 
}

所以解析“1”不会给你3。

您可以进行一个小编辑,只解析字符串的数字部分,并对您从字符串中解析int的第一次尝试进行一些小修改

if(userCom.startsWith("/dive ")){
 String intPart = userCom.split(' ')[1]; // get just the number part of the string
 int howDeep = Integer.parseInt(intPart); // parse the 'number' to an int
 myFish.dive(howDeep);}

实际上,您不必将intPart创建为单独的变量,只需将其作为参数放入parseInt方法即可。 关键是将字符串拆分到空格处,仅将第二部分拆分为解析。 这应该消除至少将字符串解析为int时出现的错误。

由于您使用Java编程,我认为使用面向对象的设计会更好。 在转换大型switch-case或long if-else-if结构时,要使用的一个好模式是将行为封装在类结构中。 在你的情况下,一个天真的方法是让Dive1,Dive2,Dive3,......更合适的设计将有一个带有距离场的Dive类。 这些是UserCommand类。 他们可能会有一个执行(Fish f)方法,它会将所需的行为应用于鱼。 现在我们还可以隔离逻辑,为用户键入的每个输入创建适当的UserCommand。 这可以通过UserCommandFactory完成。 它将有一个create(String input)方法,它将解析输入并创建正确的对象。 这种设计起初看起来更复杂,但它更灵活,更不容易出错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM