How to convert String rest="1,2,3"; in an array of integers in JAVA?

1

good night!

I have three String String cosa1 = request.getParameter("cosa1").toString(); -> SALIDAS con números aleatorios (**LOS NÚMEROS SON IDS DE PRODUCTOS**): 4,3 - 3,4,5 - 1,5,4

I want to pass that data to three INT fixes in Java, I try this and it does not work:

String cosa1 = request.getParameter("cosa1").toString();
String cosa2 = request.getParameter("cosa2").toString();
String cosa3 = request.getParameter("cosa3").toString();
int cosa_1 = Integer.parseInt("cosa1");
int cosa_2 = Integer.parseInt("cosa2");
int cosa_3 = Integer.parseInt("cosa3");

Send me the following error:

org.apache.jasper.JasperException: Ha sucedido una excepción al procesar la página JSP /registro/18-paso-23.jsp en línea 35

32:             String cosa1 = request.getParameter("cosa1").toString();
33:             String cosa2 = request.getParameter("cosa2").toString();
34:             String cosa3 = request.getParameter("cosa3").toString();
35:             int cosa_1 = Integer.parseInt("cosa1");
36:             int cosa_2 = Integer.parseInt("cosa2");
37:             int cosa_3 = Integer.parseInt("cosa3");

I hope you can help me, I already try and I can not get my array of integers.

    
asked by Ricardo Sauceda 28.09.2017 в 06:29
source

1 answer

1

If the string has incorrect values such as the, to make the cast sure you will get a NumberFormatException as it seems to be your case.

To convert to array of integers there may be many ways but I will show two, iteratively and with Streams (you must replace the variable a in thing1, thing2, etc) also with the regular expression we avoid spaces, letters.

String a = "1,2,3,4,7,a,7,, ,,";
String[] digitos =  a.split("\D+"); //
int[] resultado = new int[digitos.length];
for (int i = 0; i < resultado.length; i++) {
    resultado[i] = Integer.parseInt(digitos[i].trim());
}

System.out.println(Arrays.toString(resultado));

Exit

[1, 2, 3, 4, 7, 7]

Streams

int[] resultado= Stream.of(a.split("\D+")).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(resultado));
    
answered by 28.09.2017 / 07:09
source