I am writing code to get the coefficients and exponents of a user entered polynomial. For an example, I am entering "-3x^4+2x^3+1x^2-1x^1+8x^0" into the console. I keep getting this error:
Exception in thread "main"
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at polynomials.Driver.main(Driver.java:31)
However, when I enter a polynomial without any negative numbers (ex: "3x^4+2x^3+1x^2+1x^1+8x^0"), there is no error. I believe the error is somehow coming from the Integer.parseInt(str2), but shouldn't it be able to parse a negative integer? This makes no sense at all to me, and I couldn't find anything anywhere else.. any help would be a great help. Thanks everyone!
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter a polynomial: ");
String polynomial = userInput.nextLine();
String newPoly = polynomial.replace("-", "+-").trim();
String[] arr = newPoly.split("\\+");
for (int i = 0; i<arr.length; i++) {
System.out.println(arr[i]);
String str = arr[i].trim();
String[] arr2 = str.split("x");
String str2 = arr2[0];
System.out.println(str2); //prints coefficient
System.out.println(str.substring(str.indexOf('^')+1)); //prints exponent
System.out.println(Integer.parseInt(str2));
}
}