Created
November 28, 2020 00:39
-
-
Save Irwin1985/2b3979bf0635c6ccad33c297272b0e3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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