如何在java中将字符串数组转换为int数组

我在java程序中有一个像这样的字符串数组

String results[] = { "2", "1", "5", "1" }; 

我想将其转换为整数数组,如下所示:

 int results[] = { 2, 1, 5, 1 }; 

最后我想找到该数组的所有int元素的总和。

如果您使用的是Java 8试试这个:

  int[] array = Arrays.stream(resultsStr).mapToInt(Integer::parseInt).toArray(); 
 String resultsStr[] = {"2", "1", "5", "1"}; ArrayList intermediate = new ArrayList(); for(String str : resultsStr) { intermediate.add(Integer.parseInt(str, 10)); //the 10 could be ommitted } int resultsInt[] = intermediate.toArray(); 

并且您的resultsInt[]将包含整数数组。 虽然我同意它不必通过arraylist(它可以在没有它的情况下完成)我使用它只是因为它更容易输入。

这是我的简单解决方案:

 public class Tester { public static void main(String[] args) { // TODO Auto-generated method stub String results[]={"2","1","5","1"}; //Creating a new array of Type Int int result [] = new int[4]; int sum = 0; //Going trough every element in results And Converting it to Int By using : Integer.valueOf(String str) for (int i = 0; i < results.length; i++) { result[i] = Integer.valueOf(results[i]); } //Displaying the result for (int i = 0; i < result.length; i++) { System.out.println(result[i]); sum += result[i]; } System.out.println("The sum of all elements is : " + sum); } 

}

我可能有点晚了,但是这里有一个简单的解决方案,基本上使用for循环来遍历字符串数组,将解析后的整数值添加到新的整数数组中,并在整数过程中添加整数。 另请注意,我移动了String数组类型的方括号, String[] results ,因为它不仅不那么混乱,而且数组是类型的一部分而不是数组名称的一部分。

 public class test { public static void main(String[] args) { String[] results = { "2", "1", "5", "1" }; // Create int array with a pre-defined length based upon your example int[] integerArray = new int[results.length]; // Variable that holds the sum of your integers int sumOfIntegers = 0; // Iterate through results array and convert to integer for (int i = 0; i < results.length; i++) { integerArray[i] = Integer.parseInt(results[i]); // Add to the final sum sumOfIntegers += integerArray[i]; } System.out.println("The sum of the integers is: " + sumOfIntegers); } } 

你也可以先创建整数数组,然后在循环之后将数字加在一起,但是在这个实例中我们假设字符串数组都是整数,所以我没有看到使这个太复杂的原因。

一个简单的解决方案是:

  private void toIntArray(String[] strings) { Integer[] intArray=new Integer[strings.length]; int i=0; for(String str:strings){ intarray[i]=Integer.parseInt(str.trim()); i++; } }