1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. public class ArrayDeserializer {
  6. public static List<Integer> deserializeArray(String input, int arrayLength) throws IOException {
  7. List<Integer> result = new ArrayList<>();
  8. String[] values = input.split(","); // Split the input string by comma
  9. for (String value : values) {
  10. try {
  11. result.add(Integer.parseInt(value.trim())); // Parse each value as an integer, removing whitespace
  12. } catch (NumberFormatException e) {
  13. // Handle invalid number format (e.g., non-numeric values)
  14. System.err.println("Invalid number format: " + value);
  15. // You might choose to skip the invalid value or throw an exception.
  16. }
  17. }
  18. return result;
  19. }
  20. public static void main(String[] args) {
  21. String input = "1,2,3,4,5"; // Example input
  22. int arrayLength = 5;
  23. List<Integer> deserializedList = null;
  24. try {
  25. deserializedList = deserializeArray(input, arrayLength);
  26. System.out.println("Deserialized list: " + deserializedList);
  27. } catch (IOException e) {
  28. System.err.println("Error deserializing array: " + e.getMessage());
  29. }
  30. String input2 = "10, 20,abc, 40";
  31. int arrayLength2 = 4;
  32. List<Integer> deserializedList2 = null;
  33. try {
  34. deserializedList2 = deserializeArray(input2, arrayLength2);
  35. System.out.println("Deserialized list: " + deserializedList2);
  36. } catch (IOException e) {
  37. System.err.println("Error deserializing array: " + e.getMessage());
  38. }
  39. }
  40. }

Add your comment