user3492471
user3492471

Reputation: 93

Java method for empty input

I have a java method which is supposed to check 20 inputs parameters for empty and return a message

Example:

public String CheckEmpty(String a,String b,String c, String d,String e, String f, String g, String i,String j, String k,.....) {
    String str="";
    if(a.isEmpty()){
        str= "a is empty";
    }
    if(b.isEmpty()){
        str= "b is empty";
    }
    return str;
} 

I need to check for the if condition for all inputs? there are around 20 inputs or is there any efficient way of doing the same check in java ?

Please advise.

Upvotes: 0

Views: 2036

Answers (4)

HarshaXsoad
HarshaXsoad

Reputation: 806

  1. Take input parameters as a string array
  2. Then loop through it and check for each element's boolean representation

    for(int i = 0; i<20;i++)  
    {  
        if(null == stringInputArray[i])  
        {
        //Using **i** you can take the current empty element's index and 
          do your stuff here...
        }  
    }
    

UPDATE:

Change code to check whether element is null.

Upvotes: -1

mazhar islam
mazhar islam

Reputation: 5619

Try this:

public String CheckEmpty(List<String> argumentList) {
    for(Iterator<String> i = argumentList.iterator(); i.hasNext(); ) {
        String item = i.next();
        System.out.println(item);
    }
        return item;
}

Upvotes: 0

Jan
Jan

Reputation: 361

Use a Map(<String>, <String>) as parameter, then do the checks in a loop.

The keys of the map would be the variable names, the values of the map would be the values that you want to check.

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100269

It's better to use variable arguments like this:

public String checkEmtpy(String... args) {
    for(int i=0; i<args.length; i++) {
        if(args[i].isEmpty()) {
            return ((char)('a'+i))+" is empty";
        }
    }
    return "";
}

For example, checkEmtpy("aaa", "b", "", "ddd") returns c is empty.

Upvotes: 7

Related Questions