java - Splitting a String of a large negative number and putting it into a LinkedList -
java - Splitting a String of a large negative number and putting it into a LinkedList -
this method, numberformatexception input "-" when seek run negative number.
public newobj(string s) { list = new linkedlist<integer>(); string[] splitted = s.split("\\d"); int[] ints = new int[splitted.length]; (int = 0; < splitted.length - 1; i++) { ints[i] = integer.parseint(splitted[i]); } (int j = 0; j < ints.length - 1; j++) { list.add(ints[j]); } }
my input string number "-123456" or "12345". positive numbers work, can't negatives work.
for negative input string, want list [-1,-2,-3,-4,-5,-6].
it split number a numeric pattern if have -123
for example:
string str = "-123"; system.out.println(arrays.tostring(str.split("\\d")));
output
[-]
and -
not parsable int
from comments:
for input -123456
op wants create positive number
you can by
math.abs(integer.parseint(inputstring))
let parse negative number , can absolute value using math.abs()
further comments
op wants split each digit , apply sign, can
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()]; } (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));
note: error handling left on
java string parsing integer
Comments
Post a Comment