简体   繁体   English

可以在不使用else-if的情况下将多个if语句与单个else子句关联吗?

[英]Can multiple if statements be associated with a single else clause without using else-if?

I have a validation method in which I have to check conditions one by one and then throw error messages accordingly. 我有一种验证方法,其中必须逐个检查条件,然后相应地引发错误消息。

To achieve this, I am using multiple if statements, and if all the conditions are false, I should execute a task. 为此,我使用了多个if语句,并且如果所有条件都为false,则应该执行一个任务。

Here's my code: 这是我的代码:

if(s1.equals("") || s2.equals("") || s3.equals("") || s4.equals("") || s5.equals("") || s6.equals(""))      
    Toast.makeText(getApplicationContext(),"Enter all Details first", Toast.LENGTH_SHORT).show();       
if(!s5.matches("[A-Za-z0-9]+"))     
    e5.setError("Username cannot contain special characters");      
if(s5.length()<6)
    e5.setError("Username must be a minimum of 6 characters.");
if(!(s3.contains("@")&& s3.contains(".")))
    e3.setError("Enter a valid Email Id");      
if(!s6.equals(s7))
    e7.setError("Passwords dont match");
if(s2.length()!=10)     
    e2.setError("Please enter a valid 10 digit number");        
else
{
    Validate v2=new Validate();
    v2.store_values(s1,s2,s3,s4,s5,s6,s8);
    v2.execute();
}   

The problem is that the else statement is associated only with the last if statement, and the previous 5 if statements work independently. 问题在于else语句仅与最后一个if语句相关联,而前5个if语句独立工作。

Please note that I cannot use else-ifs, since all the fields should be validated - for example even if s3 is invalid, s6 must still be validated. 请注意,我不能使用else-ifs,因为应该验证所有字段-例如,即使s3无效,仍然必须验证s6 Therefore, all the if statements must be evaluated, regardless of how many are evaluated to true. 因此,必须评估所有的if语句,而不管有多少个评估为true。

How can I solve this problem? 我怎么解决这个问题?

The only way for multiple if statements to be associated with the same else statement is by using if-else-if...else , which is not what you need, since you want all the if statements to be evaluated, and if-else-if...else will evaluate the if statements only until one is evaluated to true. 将多个if语句与同一个else语句关联的唯一方法是使用if-else-if...else ,这不是您所需要的,因为您希望对所有if语句进行求值,而if-else-if...else将只评估if语句,直到一个被评估为true。

Instead, you can use a flag (boolean variable) that marks the input as invalid and use it instead of the else statement to determine if the input is valid. 相反,可以使用将输入标记为无效的标志(布尔变量),并使用它代替else语句来确定输入是否有效。

boolean valid = true;

if(s1.equals("") || s2.equals("") || s3.equals("") || s4.equals("") || s5.equals("") || s6.equals("")) {     
    Toast.makeText(getApplicationContext(),"Enter all Details first", Toast.LENGTH_SHORT).show();    
    valid = false;
}   
if(!s5.matches("[A-Za-z0-9]+")) {    
    e5.setError("Username cannot contain special characters");  
    valid = false;
} 
if(s5.length()<6) {
    e5.setError("Username must be a minimum of 6 characters.");
    valid = false;
} 
if(!(s3.contains("@")&& s3.contains("."))) {
    e3.setError("Enter a valid Email Id");    
    valid = false;
}   
if(!s6.equals(s7)) {
    e7.setError("Passwords dont match");
    valid = false;
} 
if(s2.length()!=10) {     
    e2.setError("Please enter a valid 10 digit number");
    valid = false;
} 
if (valid) {
    Validate v2=new Validate();
    v2.store_values(s1,s2,s3,s4,s5,s6,s8);
    v2.execute();
}

Set a boolean flag in all of your if statements. 在所有if语句中设置一个布尔标志。 If an error occured, set it to true . 如果发生错误,请将其设置为true

Then, you replace the else segment with another if statement which executes only if the boolean flag you declared is false. 然后,将else段替换为另一个if语句,该语句仅在声明的布尔标志为false时才执行。

You are using a generic datatype ( String ) to store data who's values are bound by some requirements. 您正在使用通用数据类型( String )存储值受某些要求约束的数据。 It decreases the maintainability of your code. 它降低了代码的可维护性。

A better approach would be to create datatypes which store the data. 更好的方法是创建存储数据的数据类型。 That datatype would then have additional validation logic which you could use, such as by having logic in place to reject setting the value of that datatype to something which violate your specifications. 然后,该数据类型将具有您可以使用的其他验证逻辑,例如,通过使用适当的逻辑来拒绝将该数据类型的值设置为违反您的规范的值。 An exmaple of such a datatype would be Password . 这样的数据类型的一个典范是Password Password password = new Password("abcd"); could then throw an exception given that your specifications state that a password must be of length 5 or more characters. 如果您的规范指出密码长度必须为5个或更多字符,则可能会引发异常。 Futher more, you could ensure that the password only exists in memory as plain text for a very short duration, by having the constructor hash it immediately after it has been validated. 此外,通过使构造函数在验证后立即对其进行哈希处理,可以确保密码仅在短时间内以纯文本形式存在于内存中。

If you are using Java EE, see javax.validation.Validator for a yet another approach. 如果您使用的是Java EE,请参见javax.validation.Validator ,以获取另一种方法。

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

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