Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced for loop for Strings

I am a beginner to coding. Currently I am learning arrays.

In the following code, I am trying to display the words entered by the user using a String array. The code is displaying null when using enhanced for-loop. Can anyone explain the problem?

The code is working fine with normal for-loop.

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    String word;
    int count = 0;

    String[] words = new String[100];

    System.out.println("Enter the words (enter 'done' when finished):");

    do {
        System.out.println("Enter word "+ (count+1));
        word=scanner.nextLine();

        if (!word.equalsIgnoreCase("done")) {
            words[count]=word;
            count++;
        }
    }while (!word.equalsIgnoreCase("done"));

    System.out.println("Words entered are:");

    for (String print:words){
        System.out.println(print);
    }

    scanner.close();
}

The code should display the words entered by the user but it is displaying null instead of the word.

like image 279
Manish Joshi Avatar asked Sep 05 '25 20:09

Manish Joshi


2 Answers

The enhanced for loop is not suitable in this case, since it is printing all 100 elements of the array, most of which are probably null.

When you use the regular for loop, you take advantage of the count variable, which lets you print only the initialized elements of the array:

for (int i = 0; i < count; i++) {
    System.out.println(words[i]);
}

If you insist on using the enhanced for loop, you can check for null elements, and break from the loop when you encounter the first:

for (String print:words){
    if (print != null) {
        System.out.println(print);
    } else {
        break; // once you encountered the first null, there's no point to continue the loop
    }
}
like image 190
Eran Avatar answered Sep 09 '25 19:09

Eran


You've made an array with 100 entries. Initially, all 100 of them are null. Then, your do/while loop fills in a few of them. How many depends on the user, of course.

But then, you're printing all 100 entries of the array. You'll see a few words, then lots of nulls. You might be better to print only the entries that aren't null, like this.

for (String print:words){
    if (print != null) {
        System.out.println(print);
    }
}
like image 26
Dawood ibn Kareem Avatar answered Sep 09 '25 17:09

Dawood ibn Kareem