简体   繁体   English

为什么我的Java代码没有经过if语句?

[英]Why isn't my java code proceeding past my if statements?

Okay, I have never had this problem before so I am not sure how to word it or to repair it, I am building a java application that creates dealers, in that application I have the parameters passed in to the DealerFactory.createDealer method and proceed to first check if that dealer exists with a conditional statement that looks like this: 好的,我之前从未遇到过此问题,所以我不确定如何措辞或修复它,我正在构建一个创建经销商的Java应用程序,在该应用程序中,我已将参数传递给DealerFactory.createDealer方法并继续首先用如下条件语句检查该经销商是否存在:

    if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)) {

        throw new Exception("Sorry That Dealer Already Exists");

    } else if (DealerFactory.fetchDealer(loginId).getId().equals(DNo)){

        throw new Exception("Sorry That Dealer Already Exists");

    } else {
         << proceed with the rest of the method here >>

I have seen this done before so as to check the availability of the username and the id of the person being created. 我之前已经看过此操作,以便检查用户名和正在创建的人的ID的可用性。 However after running it I found that if I create the dealer and the condition evaluates to true the if statement works just fine letting me know that I have created a user that already exists and I need to create him/her with new a different Id and username. 但是,在运行它之后,我发现如果我创建了经销商并且条件评估为true,那么if语句就可以正常工作,让我知道我已经创建了一个已经存在的用户,并且需要使用新的其他ID和用户名。 However if the condition evaluates to false I never seem to make it into the else portion of the statement, I am getting no errors, no compilation issues, and no exceptions I have written the statement differently to try that, which wasn't really any different it just looked syntactically different: 但是,如果条件的计算结果为false,我似乎永远不会进入语句的else部分,那么我不会收到任何错误,没有编译问题,也没有例外,因此我以不同的方式编写了该语句来尝试这一点,这实际上不是任何事情不同的只是语法上看起来不同:

 if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)
            || DealerFactory.fetchDealer(loginId).getId().equals(DNo)) {

        throw new Exception("Sorry That Dealer Already Exists");
    }

I have included println statements to follow the program through its run and when the condition evaluates to false I never make it into the else statement. 我包含了println语句,以在程序运行期间跟踪程序,当条件评估为false时,我永远不会将其放入else语句中。 I cant seem to figure out why it is breaking on the condition statement when it is evaluated to false, any thoughts? 我似乎无法弄清楚为什么当条件语句被评估为假时,它会在条件语句上中断,有什么想法吗?

edit::: 编辑:::

Ok so that I can be of more assistance in helping you guys help me lol here is the method in its entirety, I apologize for not posting it in the first place 好的,这样我就可以在帮助大家方面提供更多帮助,大声笑,这里是完整的方法,对于没有首先发布它,我深表歉意

public static int create(String DNo, String name, String admin,
        String loginId, String password, String callSrc, String voiSys,
        String whoCall, String callBrt, String active, String adfEmail)
        throws SQLException, Exception {

    int validateResult = 0;


    if (DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)
            || DealerFactory.fetchDealer(loginId).getId().equals(DNo)) {

        throw new Exception("Sorry That Dealer Already Exists");
    }

        try {

            DealerFactory.pool = DBConnector.getInstance();
            DealerFactory.connect = DBConnector.getConnection();
            DealerFactory.preparedStatement = connect
                    .prepareStatement("Insert Into Dealers (DNo, Dealer, Admin, Login, Password, CallSrc, VoiSys, WhoC, CBrt, Active, ADFemail) "
                            + "values(?,?,?,?,?,?,?,?,?,?,?)");
            DealerFactory.preparedStatement.setString(1, DNo);
            DealerFactory.preparedStatement.setString(2, name);
            DealerFactory.preparedStatement.setString(3, admin);
            DealerFactory.preparedStatement.setString(4, loginId);
            DealerFactory.preparedStatement.setString(5, password);
            DealerFactory.preparedStatement.setString(6, callSrc);
            DealerFactory.preparedStatement.setString(7, voiSys);
            DealerFactory.preparedStatement.setString(8, whoCall);
            DealerFactory.preparedStatement.setString(9, callBrt);
            DealerFactory.preparedStatement.setString(10, active);
            DealerFactory.preparedStatement.setString(11, adfEmail);

            validateResult = DealerFactory.preparedStatement
                    .executeUpdate();

        } catch (SQLException ex) {

            System.err.println("Error: " + ex + "\n");
            ex.printStackTrace();

        } finally {

            DBUtils.closePrepStatement(DealerFactory.preparedStatement);
            DealerFactory.pool.freeConnection(DealerFactory.connect);

        }

    return validateResult;
}

First things first, you shouldn't chain methods like that due to dangers of NullPointerException 首先,由于NullPointerException危险,您不应该像这样链接方法

So this part: 所以这部分:

if(DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId))

Could look something like this: 可能看起来像这样:

if(DealerFactory.fetchDealer(loginId) != null && 
   DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId))

Or you could have a separate null check before all your if statements. 或者,您可以在所有if语句之前进行单独的null检查。

However, what you are doing is an overkill. 但是,您正在做的事太过分了。 This whole part: 这整个部分:

DealerFactory.fetchDealer(loginId).getLoginId()

Returns null if you cannot find a dealer or loginId that you already have. 如果找不到已拥有的经销商或loginId ,则返回null Assuming your fetchDealer() method returns null if dealer cannot be found. 如果fetchDealer()代理商,则假定您的fetchDealer()方法返回null

Instead of: 代替:

if(DealerFactory.fetchDealer(loginId).getLoginId().equals(loginId)))

You can just do: 您可以这样做:

if(DealerFactory.fetchDealer(loginId) != null)

Another improvement you could do is to add a method to DealerFactory called dealerExists(String id) declared something like this: 您可以做的另一种改进是在DealerFactory添加一个名为dealerExists(String id)的方法,该方法声明如下:

boolean dealerExists(String id) {
    return (YOUR_DATA_STRUCTURE_OF_DEALERS.get(id) != null);
}

Or even: 甚至:

boolean dealerExists(String id) {
    return (fetchDealer(loginId) != null);
}

This would allow for better logical flow of your code. 这将使代码的逻辑流程更好。 Your if statement would be very clear then: 您的if陈述将非常清楚:

if(DealerFactory.dealerExists(loginId) {
    throw new Exception("Sorry That Dealer Already Exists");
}

Also, the value DNo is the dealer number I presume and you are checking if a dealer exists with the provided loginId or the provided DNo . 同样,值DNo是我假定的代理商编号,您正在检查是否存在带有提供的loginId或提供的DNo的代理商。 However, in you checks you are comparing the DNo to the loginId to check if a dealer exists. 但是,在检查中,您将DNologinId进行比较以检查是否存在经销商。 What exactly is the point of DNo and shouldn't the loginId be enough to determine that the dealer exists? DNo确切DNo是什么, loginId是否足以确定经销商存在? If you really need to check the DNo as well, just add it as a check within the methods I suggested above. 如果您确实还需要检查DNo ,只需在我上面建议的方法中将其作为检查添加即可。

More information regrading the variables that you are passing into the conditional would be of great help, (ie loginId and DNo ). 有关重新定义要传递给条件变量的更多信息,将有很大帮助(即loginIdDNo )。 The first thing I would do is simplify your conditions in the if & else if statements. 我要做的第一件事是简化ifelse if语句中的条件。

It seems like you could change the if conditional to be if(DealerFactory.fetchDealer(loginId)) and have it work just the same since if the factory returns a dealer with the ID that you are looking for, that dealer already exists. 看来您可以将if条件更改为if(DealerFactory.fetchDealer(loginId)) ,并使它的工作原理相同,因为如果工厂返回了您要查找的ID的经销商,则该经销商已经存在。 From my understanding of what you're trying to achieve, it's unnecessary to dig any deeper. 根据我对您要实现的目标的了解,没有必要进行更深入的研究。 Also try running through this section of code with the debugger and monitor variables step-by-step to see what things look like at each line of code. 还可以尝试使用调试器遍历这段代码,并逐步监视变量,以查看每一行代码的情况。

Edit: 编辑:

You could also move the expressions outside of the conditional and set them to variables. 您也可以将表达式移至条件表达式之外,并将其设置为变量。 For example: 例如:

int dealerId =  DealerFactory.fetchDealer(loginId);
if(dealerId != null && dealerId != loginId) {
      //<< proceed with the rest of the method here >>
} else {
     //<<throw exception>>
}

Checking to see if dealerId is null in the conditional would avoid NullPointerException s, and declaring things outside of the conditional will make it easier to debug by hand. 检查条件中的dealerId是否为null将避免NullPointerException ,并且声明条件之外的内容将使其更易于手动调试。

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

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