Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Filter Failure Messages | String
Java Basics

book
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.

  1. Loop through the logs array and check each message for the presence of the keyword "failure" (case-insensitive).
  2. Count how many messages contain the word "failure" and store the result in a variable count.
  3. Loop through the logs array again, and add only the messages containing "failure" into the errorLogs array.

Løsning

java

solution

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?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 5. Kapitel 4
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

expand
ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt