Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
¿Cómo convertir una matriz bidimensional de cadena en una de tipo int?

¿Cómo puedo convertir una matriz doble de tipo String en una matriz doble de tipo int?

 @PostMapping("/hole/coordinate") @ResponseBody public String saveCoordinate(@RequestBody Map<String, Object> params) { System.out.println("params = " + params); System.out.println("params = " + params.get("coordinate")); return "success"; }

System.out.println(params.get("coordinate")); store [[445, 292], [585, 331], [612, 223], [205, 532]] Hay m 2 elementos de la matriz doble. ex) [a,b],[c,d].....m En este momento, quiero recibir el resultado en el tipo de datos de int[][], no String.

Me preguntaba cómo puedo convertir de String a int[][].

Intenté como a continuación

 int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray(); for (int i : arr) { System.out.println("i = " + i); }

pero me da

 4 4 5 2 9 2 ...

¡Atentamente!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede probar el siguiente código si está intentando convertir String a int[]

 import java.util.stream.*; public class MyClass { public static void main(String args[]) { String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]"; int[] arr= Stream.of(str.replaceAll("[\\[\\]\\ ]", "").split(",")).mapToInt(Integer::parseInt).toArray(); for (int i : arr) { System.out.println("i = " + i); } } }

Imprime los siguientes valores como salida:

 i = 445 i = 292 i = 585 i = 331 i = 612 i = 223 i = 205 i = 532
over 4 years ago · Santiago Trujillo Report

0

 Try this. It creates a matrix of coordinates. String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]"; List<String> numbers = List.of(str.split(",| |\\[|\\]")); List<String> onlyNumbers = numbers.stream() .filter(number -> !number.equals("") && !number.equals(" ")) .toList(); Integer[][] coordinates = new Integer[onlyNumbers.size()][2]; int counter = 0; for(int i=0; i < onlyNumbers.size() - 1; i+=2){ coordinates[counter][0] = Integer.valueOf(onlyNumbers.get(i)); coordinates[counter][1] = Integer.valueOf(onlyNumbers.get(i+1)); counter++; }
over 4 years ago · Santiago Trujillo Report

0

Puede analizarlo manualmente, como se hizo en otras respuestas, pero como está usando spring , debe usar las herramientas que le ofrece.

Spring usa ObjectMapper de Jackson para la serialización y deserialización de forma predeterminada. Un bean de este tipo está preconfigurado para usted, puede autoconectarlo en su método de controlador y usarlo. Entonces todo el análisis es este:

 int[][] parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);

Y su método de controlador se ve así:

 @PostMapping("/hole/coordinate") @ResponseBody public String saveCoordinate(@RequestBody Map<String, Object> params, ObjectMapper objectMapper) { System.out.println("params = " + params); System.out.println("params = " + params.get("coordinate")); //get string from your params String coordinates = "[[445, 292], [585, 331], [612, 223], [205, 532]]"; int[][] parsedCoordinates; try { parsedCoordinates = objectMapper.readValue(coordinates, int[][].class); } catch (JsonProcessingException exc) { //that's a bad way to handle error, but it's an example //you might return error message like - invalid coordinate format //or whatever you need exc.printStackTrace(); throw new RuntimeException(exc); } //printing parsed result to check it for (int i = 0; i < parsedCoordinates.length; i++) { int[] inner = parsedCoordinates[i]; for (int j = 0; j < inner.length; j++) { System.out.printf("pos %d-%d, value %d%n", i, j, parsedCoordinates[i][j]); } } return "success"; }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!