Ask Question
28 May, 02:07

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)

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

+4
Answers (1)
  1. 28 May, 04:49
    0
    hasEmpty = false;

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

    if ((names[k] = = null)

    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.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the array elements ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers