这是我的方法,但是当我尝试运行负数时,我收到输入“-”的 NumberFormatException 异常。
public newObj(String s)
{
list = new LinkedList<Integer>();
String[] splitted = s.split("\\d");
int[] ints = new int[splitted.length];
for (int i = 0; i < splitted.length - 1; i++) {
ints[i] = Integer.parseInt(splitted[i]);
}
for (int j = 0; j < ints.length - 1; j++) {
list.add(ints[j]);
}
}
我的输入字符串只是一个数字,如“-123456”或“12345”。正数有效,但我无法使负数有效。
对于我的负输入字符串,我希望我的列表类似于 [-1,-2,-3,-4,-5,-6]。
最佳答案
它将按数字模式分割数字,因此如果您有-123
例如:
String str = "-123";
System.out.println(Arrays.toString(str.split("\\d")));
输出
[-]
和 -
无法解析为 int
来自评论:
对于像-123456
这样的输入,op希望将其设为正数
你可以这样做
Math.abs(Integer.parseInt(inputString))
让它解析负数,然后你可以使用Math.abs()
得到它的绝对值
进一步评论
op 想要分割每个数字并应用符号,你可以这样做
String str = "-123";
int numbers[] = null;
int characterIndex = 0;
boolean isNegative = false;
if (str.trim().startsWith("-")) {
characterIndex = 1;
isNegative = true;
numbers = new int[str.length() - 1];
} else {
numbers = new int[str.length()];
}
for (int numIndex = 0; characterIndex < str.length(); characterIndex++, numIndex++) {
numbers[numIndex] = Integer.parseInt(str.substring(characterIndex, characterIndex + 1));
if (isNegative) {
numbers[numIndex] = -1 * numbers[numIndex];
}
}
System.out.println(Arrays.toString(numbers));
注意:错误处理由您负责
关于java - 拆分一个大负数的字符串并将其放入 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24344792/