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 aNullPointerExceptionsince the inner arrays start asnull. - 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 atry-catchblock to handleNumberFormatExceptiongracefully. - Flexibility Tip: Using
parts.lengthfor 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
相关产品推荐
相关产品推荐

