So, as a personal project.. I'm making a Program to solve for Derivatives of any 1-variable equation.. Which includes (for those of you who remember Calculus) the power rule, product rule, quotient rule, chain rule... etc..
So here is my code for the getExponent Method!
public int getExponent(String userInput){ String string = ""; for(int a = getVariable(userInput).length(); a < userInput.length(); a++){ int digit = userInput.charAt(a)-48; if(digit <= 9 && digit >= 0) string += digit + ""; else break; } int newExponent = Integer.parseInt(string); return newExponent; }
Now, I have two other methods.. getCoefficient and getVariable... The getCoefficient method does the exact same as this method, however, it starts checking the characters after the variable (or the exponential portion)... Let me show you my predicament
Sample Input:
5x^2
Output:
5 - Coefficient
x^ - Variable
2 - Exponent
Now that's all nice and dandy, but when it comes to this...
Input:
5x^2 + 5x^3
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Num berFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at Input.getExponent(Input.java:51)
at Main.main(Main.java:16)
It says that I'm accepting a non integer value, and trying to parse that into an Integer.. However in my code, I clearly state that if the 'int digit' is not within the range of 0-9, to break from the loop... The getCoefficient method works just fine using extremely similar code (they start at different positions). Any tips please?
EDIT: I just checked out something, and if I change the "int a = getVariable(userInput).length()" to int a = 0... It works just fine and establishes the break whenever a non digit comes by... However, I want the variable a to start where the getVariable method ends.. How can I do this?