-1

I am trying to get the exponents of a polynomial in java.

I found something similar here How to extract polynomial coefficients in java? but I can't seem to be able to modify that for my needs, the argument of the .split() method.

I tried this:

public static void main(String[] args) { 


Scanner scanner = new Scanner(System.in);
String s1 = new String();
System.out.println("Enter a polynome:");
s1 = scanner.nextLine();
    scanner.close();

String[] Exponents = s1.split("\\-?\\+?\\dx\\^");
for (String exponent : Exponents) {
    System.out.println("Exponents:");
    System.out.println(exponent);
    }

for input: -2x^2+3x^1+6 the output is:

Exponents:

Exponents: 2

Exponents: 1+6

Thanks for the help,

Community
  • 1
  • 1
staynless
  • 86
  • 8
  • Can you show the polynomial whose coefficients you are trying to extract? Examples usually help. So does showing any attempts you have made. – Floris Mar 10 '14 at 23:44
  • `.split` is a blunt tool that may not be good enough for this use. Try regular expressions. – ajb Mar 10 '14 at 23:46
  • Or hand-write logic the scans the string searching for ^ and extracts the number immediately following. Or, overkill for your current problem, implement a recursive-descent expression parser, which would be able to handle things like x^(y+2)... – keshlam Mar 10 '14 at 23:55

1 Answers1

1

You probably want to split on + and - to get the individual terms. Then for each term, use split again to return whatever comes after the ^, or 0 if there's no ^.

String[] terms = expression.split("(-|\\+)");
for (String term : terms) {
    String[] parts = term.split("\\^");
    System.out.println("Exponent: " + (parts.length > 1 ? parts[1] : "0"));
}
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110