Recap - Control Flow
Part of the Logic & Flow section of Coddy's Java journey — lesson 39 of 59.
Challenge
Create a method named processArray that takes two arguments:
- A 1D array of Objects (
data) containing mixed types (Integer, String, or Double) - A String (
type) for processing type: "sum" or "find"
Your solution should demonstrate these concepts:
- Use guard clauses to validate input at the start of the method
- Use instanceof pattern matching to check and cast types (e.g.,
if (value instanceof Integer i)) - Use switch expressions with arrow syntax (e.g.,
switch (type) -> {) - Use labeled loops with break or continue (e.g.,
search: for())
Processing rules:
- "sum": Add all numeric values (ignore strings)
- "find": Find first numeric value greater than 100
Return messages should be:
- If array is null or empty: return "Invalid input"
- If type is invalid: return "Invalid type"
- For "sum": return "Sum: X"
- For "find": return index of found value or "Not found"
Try it yourself
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static String processArray(Object[] data, String type) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String dataJson = scanner.nextLine();
String type = scanner.nextLine();
Type arrayType = new TypeToken<Object[]>(){}.getType();
Object[] data = new Gson().fromJson(dataJson, arrayType);
System.out.println(processArray(data, type));
}
}All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow