204k views
5 votes
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++)

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: =

1 Answer

1 vote

Answer:

hasEmpty = false;

for (int k = 0; k < names.length; k++)

Step-by-step explanation:

The code run successfully from my own end. I just modify the integer declaration for k to be within the for loop initialization even though it is not really much an issue.

Better still you can use names[k].isEmpty() to check if an element is empty.

public class MyClass {

public static void main(String args[]) {

String[] names = new String[]{"John", "doe", "", "James", "Smith"};

boolean hasEmpty = false;

for (int k = 0; k < names.length; k++)

{

if ((names[k] == null) || (names[k].isEmpty()))

//if ((names[k] == null) || (names[k].equals("")))

{

hasEmpty = true;

}

}

System.out.println(hasEmpty);

}

}

Using any of the commented if-statement will work correctly. In the above sample, I got an out of true. My sample array contain one empty element.

User Ququzone
by
7.5k points