Reputation: 95
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.
Upvotes: 4
Views: 10278
Reputation: 15443
If you look closely it does print the words entered by the user. You are seeing null
because the size of your array is 100.
String[] words = new String[100];
Scroll up in your console to see the names originally entered by the user. You see nulls because the remaining elements in the array are null
. For eg: if the user enters 5 words the remaining 95 words in the array are null
.
You can add a null check to print out only the non-null values.
for (String print : words) {
if (print != null) {
System.out.println(print);
}
}
If you are using java-8
, you could just do :
Arrays.stream(words).filter(Objects::nonNull).forEach(System.out::println);
Upvotes: 1
Reputation: 393986
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
}
}
Upvotes: 4
Reputation: 79876
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);
}
}
Upvotes: 2