Complete the code to print each number in the array using an enhanced for loop.
int[] numbers = {1, 2, 3, 4, 5};
for ([1] num : numbers) {
System.out.println(num);
}The enhanced for loop requires the type of the elements in the array. Since numbers is an int array, the type is int.
Complete the code to sum all elements in the array using an enhanced for loop.
int[] values = {10, 20, 30};
int sum = 0;
for (int [1] : values) {
sum += [1];
}
System.out.println(sum);The variable name inside the loop can be any valid identifier. Here, val is used consistently.
Fix the error in the enhanced for loop to print each string in the array.
String[] fruits = {"apple", "banana", "cherry"};
for ([1] fruit : fruits) {
System.out.println(fruit);
}The array contains strings, so the loop variable must be of type String.
Fill both blanks to create a map of word lengths for words longer than 3 characters.
String[] words = {"cat", "elephant", "dog", "lion"};
Map<String, Integer> lengths = new HashMap<>();
for ([1] word : words) {
if (word.length() [2] 3) {
lengths.put(word, word.length());
}
}The loop variable must be String because the array contains strings. The condition checks if the word length is greater than 3.
Fill all three blanks to create a map of uppercase words and their lengths for words shorter than 5 characters.
String[] words = {"tree", "house", "car", "boat"};
Map<String, Integer> map = new HashMap<>();
for ([1] word : words) {
if (word.length() [2] 5) {
map.put(word.[3](), word.length());
}
}The loop variable is String. The condition checks for words shorter than 5 characters using <. The method toUpperCase() converts the word to uppercase before putting it in the map.