Java将数字字符串转为数组时负号开头得到-3的问题如何解决?
问题根因
- 字符
'-'的ASCII码值为45,字符'0'的ASCII码值为48,你直接对所有字符执行char - '0'操作时,负号会被计算为45-48=-3,这就是首元素异常的核心原因 - 你的需求中负号是和紧随其后的第一个数字绑定为负数,不属于单独的数字元素,因此不能直接按原字符串长度创建数组,也不能逐字符无差别转换
修复方案
单独判断字符串首位是否为负号,分情况处理数组长度和元素转换逻辑即可,修复后的完整代码如下:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class NumStrConvert { public static void main(String[] args) { BufferedReader objReader = null; try { String strCurrentLine; objReader = new BufferedReader(new FileReader("D:\\TokenNumbersData.txt")); while ((strCurrentLine = objReader.readLine()) != null) { boolean isNegative = strCurrentLine.startsWith("-"); // 负号不算数字元素,数组长度对应调整 int[] arr = new int[isNegative ? strCurrentLine.length() - 1 : strCurrentLine.length()]; int arrIndex = 0; for (int i = 0; i < strCurrentLine.length(); i++) { char c = strCurrentLine.charAt(i); if (i == 0 && isNegative) { // 首字符是负号,和下一个字符绑定为负数 int num = strCurrentLine.charAt(++i) - '0'; arr[arrIndex++] = -num; continue; } arr[arrIndex++] = c - '0'; } System.out.println(Arrays.toString(arr)); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流避免资源泄漏 try { if (objReader != null) objReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
效果验证
输入数字字符串-972754时输出为[-9, 7, 2, 7, 5, 4],符合预期;正数输入的转换逻辑和原有逻辑完全一致,不会影响原有功能。
内容的提问来源于stack exchange,提问作者JohnDoe619
相关产品推荐
相关产品推荐

