Skip to content

Instantly share code, notes, and snippets.

@Irwin1985
Created November 28, 2020 00:39
Show Gist options
  • Save Irwin1985/2b3979bf0635c6ccad33c297272b0e3a to your computer and use it in GitHub Desktop.
Save Irwin1985/2b3979bf0635c6ccad33c297272b0e3a to your computer and use it in GitHub Desktop.
public class ParsingNumbers {
static String expression;
static int currentCharPosition;
static char Look;
static double result;
// parse integer or double of any length.
public static double parseNum() {
double number = 0.0;
int digit = 0;
double scale = 1;
// parse integer part
if (Look != '.') {
while (Character.isDigit(Look)) {
digit = Character.getNumericValue(Look);
number = number * 10 + digit;
nextChar();
}
}
// parse decimal part
if (Look == '.') {
nextChar(); // eat the '.'
while (Character.isDigit(Look)) {
scale = scale * 0.1;
digit = Character.getNumericValue(Look);
number = number + (scale * digit);
nextChar();
}
}
return number;
}
// advance the next char from input.
private static void nextChar() {
if (currentCharPosition < expression.length()) {
Look = expression.charAt(currentCharPosition);
currentCharPosition += 1;
} else {
Look = ' '; // mark end of input.
}
}
// test
public static void main(String[] args) {
expression = "1985.35";
nextChar(); // start the current char.
System.out.println("Number Result: " + parseNum());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment