0
0
Javaprogramming~10 mins

Enhanced for loop in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print each number in the array using an enhanced for loop.

Java
int[] numbers = {1, 2, 3, 4, 5};
for ([1] num : numbers) {
    System.out.println(num);
}
Drag options to blanks, or click blank then click option'
Aint
Bboolean
Cdouble
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong type like String or boolean causes a compile error.
2fill in blank
medium

Complete the code to sum all elements in the array using an enhanced for loop.

Java
int[] values = {10, 20, 30};
int sum = 0;
for (int [1] : values) {
    sum += [1];
}
System.out.println(sum);
Drag options to blanks, or click blank then click option'
Ai
Bnum
Cval
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inside and outside the loop body causes errors.
3fill in blank
hard

Fix the error in the enhanced for loop to print each string in the array.

Java
String[] fruits = {"apple", "banana", "cherry"};
for ([1] fruit : fruits) {
    System.out.println(fruit);
}
Drag options to blanks, or click blank then click option'
Aboolean
Bint
Cchar
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong type like int or char causes a compile error.
4fill in blank
hard

Fill both blanks to create a map of word lengths for words longer than 3 characters.

Java
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());
    }
}
Drag options to blanks, or click blank then click option'
AString
B>
C<
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong types or wrong comparison operators.
5fill in blank
hard

Fill all three blanks to create a map of uppercase words and their lengths for words shorter than 5 characters.

Java
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());
    }
}
Drag options to blanks, or click blank then click option'
AString
B<
CtoUpperCase
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operators or method names causes errors.