+ 1

How I convert string array to a integer?

String str[] = {2,1,4}; How to get this output into a integer ?like value= 214??

9th May 2021, 12:27 PM
Soharab Uddin Mondal
Soharab Uddin Mondal - avatar
5 Respostas
+ 1
You can also work with Integer.valueOf(); String[] arr = {"2", "1", "4"}; String str = ""; //creates the String "214" for(String s : arr){ str += s; } int num = Integer.valueOf(str); System.out.println(num);
9th May 2021, 8:10 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
I solved this 2 ways represented by 2 methods below. Notice that I turned your String array into an array of int since String str[] = {2, 1, 4} can't compile: import java.util.*; public class Program { private static int arrayToInt(int[] digitArray) { int result = digitArray[0]; for (int i = 1; i < digitArray.length; i++) { result *= 10; result += digitArray[i]; } return result; } private static int arrayToInt2(int[] digits) { return Integer.parseInt(Arrays.toString(digits).replaceAll("[\\[\\]\\,\\s]", "")); } public static void main(String[] args) { int digits[] = {2,1,4}; System.out.println(arrayToInt(digits)); System.out.println(arrayToInt2(digits)); } }
9th May 2021, 12:57 PM
Josh Greig
Josh Greig - avatar
+ 2
Denise, yeah. That's similar to my arrayToInt2 method which converts the array to a string, removes the undesirable brackets, commas, and whitespaces, before using Integer.parseInt.
10th May 2021, 4:59 AM
Josh Greig
Josh Greig - avatar
+ 1
Josh Greig Yes. I just wanted to show that you also can convert a String array to int. I like your regex solution.
10th May 2021, 1:23 PM
Denise Roßberg
Denise Roßberg - avatar
0
Thank you so much sir
9th May 2021, 1:17 PM
Soharab Uddin Mondal
Soharab Uddin Mondal - avatar