简体   繁体   中英

Java - How check if array there is value or not

i have a code where i create a .xlsm file, in determined part, the code does a mysql select and set the resulset in a array, and i have to check this array if are empty or not. But, or, it returns true everytime, or, it returns false everytime. This select for example, there is a value in 296th index, and other in 322th index, but, this time, the empty boolean it is returning me true , where, were to return false , 'cause there is value in the array. i tried some things, but, i got nothing solution.

What am i doing wrong ?

This my java code:

ResultSet check_name = connect.createStatement().executeQuery("select `name` from `company`"); 
ArrayList<String> names = new ArrayList<String>(); boolean empty = true;

while(check_name.next()){ 
 names.add(name.getString("name")); 
} 

for(int l = 0; l < names.size(); l++){
 if(names.get(l).contains("[0-9a-zA-Z]+")){
  empty = false; break; 
 } 
}

if(empty == true){
 cell = row.createCell(26);
 cell.setCellValue("it's empty");
}else{
 cell = row.createCell(26);
 cell.setCellValue("it's not empty");
}

You should use trim() and isEmpty() methods of String class.

for(int l = 0; l < names.size(); l++){
 if(names.get(l)!=null && !(names.get(l).trim().isEmpty())){
  empty = false; break; 
 } 
}

This statement is the culprit:

if(names.get(l).contains("[0-9a-zA-Z]+"))

I think you were trying to do some kind of regex, but it simply checks if the string contains this value: "[0-9a-zA-Z]+"

It must be false in your case always and hence your empty flag is always true!

Contains is looking for a char sequence, not a regex. So, it is not matching what you expect.

You should use isEmpty() instead. if(!names.get(l).isEmpty())

        for(int l = 0; l < names.size(); l++){
    String name = name.get(l);
if(name.equals("")){
Log.d("TEXT ?","Doesn't CONTAIN TEXT");
}else{
Log.d("TEXT ?","CONTAIN TEXT");
}

  }

Why are you going in such mess when you simply check if the String contains null value or not . Let me know if this work , Mark it as answered if this works .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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