Challenge: Filter Failure Messages
Opgave
Swipe to start coding
Imagine you have a list of system messages, and you need to extract only those containing the word "failure".
Write a program that creates a new array with only these messages and then prints them to the console.
- Loop through the
logs
array and check each message for the presence of the keyword "failure" (case-insensitive). - Count how many messages contain the word "failure" and store the result in a variable
count
. - Loop through the
logs
array again, and add only the messages containing "failure" into theerrorLogs
array.
Løsning
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
public class Main {
public static String[] extractFailureLogs(String[] logs) {
int count = 0;
for (String log : logs) {
if (log.toLowerCase().contains("failure")) {
count++;
}
}
String[] errorLogs = new String[count];
int index = 0;
for (String log : logs) {
if (log.toLowerCase().contains("failure")) {
errorLogs[index++] = log;
}
}
return errorLogs;
}
public static void main(String[] args) {
String[] logs = {
"System started successfully",
"Failure: Disk space is low",
"User logged in",
"Warning: High CPU usage",
"Failure: Unable to connect to server",
"Backup completed"
};
String[] filtered = extractFailureLogs(logs);
System.out.println("Messages containing the keyword 'failure':");
for (String log : filtered) {
Var alt klart?
Tak for dine kommentarer!
Sektion 5. Kapitel 4
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
public class Main {
public static String[] extractFailureLogs(String[] logs) {
int count = 0;
for (___) {
if (___) {
count++;
}
}
String[] errorLogs = new String[count];
int index = 0;
for (___) {
if (___) {
errorLogs[index++] = log;
}
}
return errorLogs;
}
public static void main(String[] args) {
String[] logs = {
"System started successfully",
"Failure: Disk space is low",
"User logged in",
"Warning: High CPU usage",
"Failure: Unable to connect to server",
"Backup completed"
};
String[] filtered = extractFailureLogs(logs);
System.out.println("Messages containing the keyword 'failure':");
for (String log : filtered) {
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat