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

时间:2014-07-16 19:58:44

标签: java if-statement

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

好的,所以我在java和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英尺,这是一个错字现在已经修好......

4 个答案:

答案 0 :(得分:8)

这是一个好主意,不幸的是,您正在尝试使用非数字字符解析字符串作为int。您需要从字符串中对Int进行子字符串,如下所示:

if(userCom.startsWith("/dive")){
   String str = userCom.subString(6);
   int howDeep = Integer.parseInt(str);
   myFish.dive(howDeep);
}

答案 1 :(得分:4)

自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。

答案 2 :(得分:0)

您可以进行一个小编辑,只解析字符串的数字部分,并对您从字符串中解析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时出现的错误。

答案 3 :(得分:0)

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

相关问题