Java 拆分一个大负数字符串并将其放入LinkedList
这是我的方法,但当我尝试为负数运行它时,我得到了一个输入的NumberFormatExceptionJava 拆分一个大负数字符串并将其放入LinkedList,java,string,parsing,integer,Java,String,Parsing,Integer,这是我的方法,但当我尝试为负数运行它时,我得到了一个输入的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 -
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")));
输出
and-不能解析为int
从评论中:
对于像-123456这样的输入,op希望将其设为正数
你可以自己做
Math.abs(Integer.parseInt(inputString))
让它解析负数,然后使用
进一步评论
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));
注意:错误处理留给您它将用数字模式分割数字,因此如果您有-123 例如:
String str = "-123";
System.out.println(Arrays.toString(str.split("\\d")));
输出
and-不能解析为int
从评论中:
对于像-123456这样的输入,op希望将其设为正数
你可以自己做
Math.abs(Integer.parseInt(inputString))
让它解析负数,然后使用
进一步评论
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));
注意:错误处理留给您了根据Ren8888,您的输入字符串是什么?根据Ren8888,您的输入字符串是什么?当我将其添加到列表中时,是否可以跳过-然后将每个数字乘以-1?您的输入字符串示例是什么样的?示例将是-123456,但我也必须处理像123456这样的正数对不起,我不是说我想把它转换成正数。我的意思是输入字符串可以是正的,也可以是负的。到目前为止,我的代码适用于正数,但我不能让它适用于负数。我想我已经找到了解决问题的方法,但我只是不知道如何解析负数字符串并将其拆分为单独的负整数。你可以用同样的方法解析负数,例如Integer。当我将其添加到列表中时,parseInt-123将返回int-123,我可以跳过-,然后把每个数字都乘以-1吗?你的输入字符串样本是什么样子的?样本应该是-123456,但我也必须处理像123456这样的正数对不起,我不是想把它转换成正数。我的意思是输入字符串可以是正的,也可以是负的。到目前为止,我的代码适用于正数,但我不能让它适用于负数。我想我已经找到了解决问题的方法,但我不知道如何解析一个负数字符串并将其拆分为单独的负整数。你可以用同样的方法解析负数,例如Integer.parseInt-123将返回int-123