+ 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??
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);
+ 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));
}
}
+ 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.
+ 1
Josh Greig Yes. I just wanted to show that you also can convert a String array to int.
I like your regex solution.
0
Thank you so much sir