负值的输出总是-3



我一直在尝试将一串数字转换为数组,但每当它在字符串的开始检测到负数时,它就变成-3。有人知道怎么解决这个问题吗?这是我必须完成的3和问题的一部分,需要输入。txt格式的数字。

例如,当它接收到数字519718时,结果是[5,1,9,7,1,8]

然而,当它接收到数字-972754时,结果是[-3,9,7,2,7,5,4]

我想让它变成[-9,7,2,7,5,4]

下面的代码

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) {
int[] arr = new int[strCurrentLine.length()];
for (int i = 0; i < strCurrentLine.length(); i++)
{
arr[i] = strCurrentLine.charAt(i) - '0';
}
System.out.println(Arrays.toString(arr));
}
}

首先,实现将字符串解析为int数组的功能作为一个单独的函数/方法是有意义的。

第二,如果-符号可能只出现在输入字符串的开头,则可以使用标志并更改字符串中索引的计算:

public static int[] getDigits(String str) {
if (str == null || str.isEmpty()) {
return new int[0];
}
int hasNegative = str.charAt(0) == '-' ? 1 : 0;
int[] result = new int[str.length() - hasNegative];

for (int i = 0; i < result.length; i++) {
result[i] = Character.getNumericValue(str.charAt(i + hasNegative));
if (i == 0 && hasNegative != 0) {
result[i] *= -1;
}
}
return result;
}

测试:

System.out.println("-972754 -> " + Arrays.toString(getDigits("-972754")));
System.out.println(" 567092 -> " + Arrays.toString(getDigits("567092")));

输出:

-972754 -> [-9, 7, 2, 7, 5, 4]
567092 -> [5, 6, 7, 0, 9, 2]

最新更新