You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何将二维String数组转换为二维int数组?附代码片段

Convert 2D String Array to 2D int Array in Java

Got it, let's wrap up this code to get your conversion working today. You've already laid the groundwork, so we just need to fill in the missing pieces to handle per-element conversion and proper array initialization.

Complete Working Code

// Your target input array as provided
String[][] parts = {{"25","3","18"},{"20","12","18"},{"1","1","15"}};
int[][] stringToInt = new int[parts.length][]; 

for(int a = 0; a < parts.length; a++){
    // First, initialize the inner int array for each row (prevents NullPointerException)
    stringToInt[a] = new int[3]; 
    for(int b = 0; b < 3; b++){
        // Convert each String element to its int equivalent
        stringToInt[a][b] = Integer.parseInt(parts[a][b]);
    }
}

// Optional: Test to confirm the conversion works
for(int[] row : stringToInt){
    for(int num : row){
        System.out.print(num + " ");
    }
    System.out.println();
}

Key Notes to Understand the Logic

  • Inner Array Initialization: We have to explicitly create the inner int array with stringToInt[a] = new int[3]; before assigning values—otherwise, you’d hit a NullPointerException since the inner arrays start as null.
  • String-to-Int Conversion: Integer.parseInt() safely converts valid numeric strings to integers. If you ever risk having non-numeric values in your input, wrap this line in a try-catch block to handle NumberFormatException gracefully.
  • Flexibility Tip: Using parts.length for the outer loop keeps the code adaptable if the number of rows changes later, while hardcoding the inner loop limit to 3 makes sense since you know each row has exactly 3 elements.

Example Output

When you run the test code, you’ll get:

25 3 18 
20 12 18 
1 1 15 

内容的提问来源于stack exchange,提问作者Oliver Tworkowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:27:07