Java中数组内字符串转Integer抛出“Unknown Source Error”问题
Hey there! Let's dig into that frustrating "Unknown Source Error" you're hitting when trying to parse poi_id from your CSV data. That generic error message is usually masking a more specific issue with the data itself or how you're processing it—let's break down the most likely culprits and fixes:
Common Causes & Fixes
1. Hidden Whitespace in the poi_id Field
CSV lines often have accidental spaces around values (like user_id, 456, times_visited). When you split on commas, the poi_id string ends up being " 456" instead of "456"—and Integer.parseInt() can't handle leading/trailing spaces.
Fix: Trim the string before parsing:
int poiId = Integer.parseInt(parts[1].trim());
2. Non-Numeric or Empty poi_id Values
If any row has a poi_id that's not a pure number (like user_id, abc789, times_visited) or is empty (user_id, , times_visited), parseInt() will throw a NumberFormatException—which might get wrapped into that vague "Unknown Source" error.
Fix: Add validation before parsing to catch bad data:
String poiIdStr = parts[1].trim(); if (!poiIdStr.isEmpty() && poiIdStr.matches("\\d+")) { int poiId = Integer.parseInt(poiIdStr); // Add to your poi_list here } else { // Log or handle invalid entries instead of crashing System.err.println("Skipping line with invalid poi_id: " + poiIdStr); }
3. Malformed CSV Lines (Incorrect Number of Fields)
If some rows don't have exactly 3 values (e.g., a missing field like user_id, times_visited), splitting the line will give you an array shorter than 3 elements. Trying to access parts[1] here will throw an ArrayIndexOutOfBoundsException, which could also show up as an "Unknown Source" error.
Fix: Validate the split array length first:
String[] parts = line.split(","); if (parts.length == 3) { // Proceed with parsing } else { System.err.println("Skipping malformed line: " + line); }
4. Capture Specific Exceptions for Debugging
That "Unknown Source" error is likely because you're not catching the specific exception thrown by parseInt(). Wrapping the parsing code in a try-catch block will reveal the exact issue.
Fix: Add exception handling to get clear debug info:
try { int poiId = Integer.parseInt(parts[1].trim()); poi_list.add(new POI(poiId, ...)); // Adjust to match your POI constructor } catch (NumberFormatException e) { System.err.println("Failed to parse poi_id from line: " + line); e.printStackTrace(); // This will show the full stack trace to pinpoint the problem } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Line has missing fields: " + line); e.printStackTrace(); }
Quick Summary
Start by trimming whitespace from the poi_id string, then validate that your CSV lines are properly formatted and contain numeric poi_id values. Adding specific exception handling will help you debug exactly which lines are causing the issue instead of dealing with that vague "Unknown Source" error.
内容的提问来源于stack exchange,提问作者Efthimis_28

