import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayDeserializer {
public static List<Integer> deserializeArray(String input, int arrayLength) throws IOException {
List<Integer> result = new ArrayList<>();
String[] values = input.split(","); // Split the input string by comma
for (String value : values) {
try {
result.add(Integer.parseInt(value.trim())); // Parse each value as an integer, removing whitespace
} catch (NumberFormatException e) {
// Handle invalid number format (e.g., non-numeric values)
System.err.println("Invalid number format: " + value);
// You might choose to skip the invalid value or throw an exception.
}
}
return result;
}
public static void main(String[] args) {
String input = "1,2,3,4,5"; // Example input
int arrayLength = 5;
List<Integer> deserializedList = null;
try {
deserializedList = deserializeArray(input, arrayLength);
System.out.println("Deserialized list: " + deserializedList);
} catch (IOException e) {
System.err.println("Error deserializing array: " + e.getMessage());
}
String input2 = "10, 20,abc, 40";
int arrayLength2 = 4;
List<Integer> deserializedList2 = null;
try {
deserializedList2 = deserializeArray(input2, arrayLength2);
System.out.println("Deserialized list: " + deserializedList2);
} catch (IOException e) {
System.err.println("Error deserializing array: " + e.getMessage());
}
}
}
Add your comment