Exercise: An array of Strings, names, has been declared and initialized. Write t
ID: 3691058 • Letter: E
Question
Exercise: An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false.
This is the code I put in, but it has compile errors
hasEmpty = false;
int k = 0;
for (k = 0; k < names.length; k++)
{
if ((names[k] == null) || (names[k].equals("")))
hasEmpty = true;
}
Remarks and Hints:
You need a main method here
There is no need to declare anything in this exercise.
You almost certainly should be using: String, System, main, out, static
Correct Solutions that use 0 tend to also use exit
Solutions with your approach don't usually use: =
Explanation / Answer
Hi, Please test with your array. It is working fine for me.
public class ArrayCheck {
public static boolean checkEmpty(String names[]){
boolean hasEmpty = false;
int k = 0;
for (k = 0; k < names.length; k++)
{
if ((names[k] == null) || (names[k].equals("")))
hasEmpty = true;
}
return hasEmpty;
}
public static void main(String[] args) {
// array decalration
String names[] = {
"Alex",
"Bob",
"",
"Preddw"
};
System.out.println(checkEmpty(names));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.