Question

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,

Was it helpful?

Solution

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"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top