Java将String []转换为int [] [英] Java convert String[] to int[]

查看:142
本文介绍了Java将String []转换为int []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String [],其中每个元素都可以转换为整数。我可以将它转换为int []的最佳方法是什么?

I have a String[], where each element is convertible to an integer. What's the best way I can convert this to an int[]?

int[] StringArrayToIntArray(String[] s)
{
    ... ? ...
}


推荐答案

public static int[] StringArrToIntArr(String[] s) {
   int[] result = new int[s.length];
   for (int i = 0; i < s.length; i++) {
      result[i] = Integer.parseInt(s[i]);
   }
   return result;
}

只需遍历字符串数组并转换每个元素。

Simply iterate through the string array and convert each element.

注意:如果您的任何元素无法解析为 int ,则此方法将引发异常。为了防止这种情况发生,每次调用 Integer.parseInt()都应放在 try / catch 块中。

Note: If any of your elements fail to parse to an int this method will throw an exception. To keep that from happening each call to Integer.parseInt() should be placed in a try/catch block.

这篇关于Java将String []转换为int []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆