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

book
Challenge: Filter Failure Messages

Uppgift

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 allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 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) {

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

We use cookies to make your experience better!
some-alt