Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveEvenLength.java
More file actions
Latest commit
63 lines (49 loc) · 1.88 KB
/
Copy pathRemoveEvenLength.java
File metadata and controls
63 lines (49 loc) · 1.88 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
importjava.util.ArrayList;
importjava.util.Scanner;
publicclassRemoveEvenLength {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
System.out.println("Remove Even Length Strings");
System.out.println("-------------------------");
// Create an ArrayList of strings
ArrayList<String> strings = newArrayList<>();
// Get input from user
System.out.println("Enter strings (enter 'done' to finish):");
while (true) {
System.out.print("> ");
Stringinput = scanner.nextLine().trim();
if (input.equalsIgnoreCase("done")) {
break;
}
strings.add(input);
}
// Display the original list
System.out.println("\nOriginal list:");
displayList(strings);
// Remove strings of even length
removeEvenLength(strings);
// Display the modified list
System.out.println("\nAfter removing even length strings:");
displayList(strings);
scanner.close();
}
// Method to remove strings of even length from an ArrayList
publicstaticvoidremoveEvenLength(ArrayList<String> list) {
// Use an index-based approach to handle removal during iteration
for (inti = list.size() - 1; i >= 0; i--) {
if (list.get(i).length() % 2 == 0) {
list.remove(i);
}
}
}
// Helper method to display the list
privatestaticvoiddisplayList(ArrayList<String> list) {
if (list.isEmpty()) {
System.out.println("(empty list)");
return;
}
for (Stringstr : list) {
System.out.println("\"" + str + "\" (length: " + str.length() + ")");
}
}
}