Created
March 4, 2018 12:50
-
-
Save anikseu/ae517405194daaf1ddeef6bf30a8bdb0 to your computer and use it in GitHub Desktop.
CSE2015 Homework March 5, 2018
This file contains hidden or 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 TextToInteger { | |
| public static void main(String[] args) { | |
| String text = "+1234"; | |
| int number = convertToInteger(text); | |
| //number++; | |
| System.out.println(number); | |
| } | |
| // Homework: | |
| // modify this code to make it work for both positive | |
| // and negative integers | |
| // write another method that works for floating point | |
| // numbers | |
| // Reference: study Horner's rule for evaluating polynomials | |
| // P(x) = 2x^2 - 5x + 20 | |
| private static int convertToInteger(String text) { | |
| int number = 0; | |
| // case: negative number | |
| if(text.charAt(0)=='-'){ | |
| for (int i = 1; i < text.length(); i++){ | |
| char ch = text.charAt(i); | |
| int digit = ch - '0'; | |
| number = number * 10 + digit; | |
| } | |
| number *= -1; | |
| } | |
| // case: positive number with "+" sign given | |
| else if(text.charAt(0)=='+'){ | |
| for (int i = 1; i < text.length(); i++){ | |
| char ch = text.charAt(i); | |
| int digit = ch - '0'; | |
| number = number * 10 + digit; | |
| } | |
| } | |
| // case: positive number | |
| else{ | |
| for (int i = 0; i < text.length(); i++) { | |
| char ch = text.charAt(i); | |
| int digit = ch - '0'; | |
| number = number * 10 + digit; | |
| } | |
| } | |
| return number; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment