I'm making a program that takes the users input as a string. Within that string, if i know the position of where the number is, how do i separate the number with its value saved as a variable?
Asked
Active
Viewed 156 times
2 Answers
2
int newValue = Integer.ParseInt(string.substring(begin, end));
begin
is the position where the number begins. end
is the position where it ends. Note that the first character is 0, second is 1, nth is n-1, etc, etc.-
You can also get a double:
double newValue = Double.ParseDouble(string.substring(begin, end));

nanofarad
- 40,330
- 4
- 86
- 117
-
Thanks!That helps A LOT... But is there a way to get a double(decimal)? – user2530080 Jun 28 '13 at 00:57
0
You need to get the integer part out of the string using regex "[\\D]"
and then convert the integer string to int value. Something like :
try {
int val = Integer.parseInt(strValue.replaceAll("[\\D]", ""));
} catch(NumberFormatException nfe) {
}

Juned Ahsan
- 67,789
- 12
- 98
- 136
-
No, the user knows the number may be part of the string. You need to split first. – nanofarad Jun 28 '13 at 00:24