Method return type problem
Here is my program. It is supposed to take the derivative of a given function and display it.
Code:
import java.util.Scanner;
public class Derivative {
private double power;
private double coefficient;
private String variable;
public Scanner scanner;
static Derivative d = new Derivative();
String[] terms;
String[] derivative;
public static void main(String args[]) {
System.out.println("The derivative of " + args[1] + " is\n");
System.out.println(d.getDerivative(args[1]));
}
public void setPower(double power) {
this.power = power;
}
public double getPower() {
return power;
}
public void setCoefficient(double coefficient) {
this.coefficient = coefficient;
}
public double getCoefficient() {
return coefficient;
}
public void setVariable(String variable) {
this.variable = variable;
}
public String getVariable() {
return variable;
}
public String getDerivative(String function)
{
analyze(function); //analyze the function given
String answer = "";
differentiate(function); //differentiate the function
for(int i = 0; i < derivative.length; i++)
answer = answer + derivative[i];
return answer;
}
public void analyze(String function) {
scanner = new Scanner(function); //pass the function to the scanner
int x = 1;
String[] terms = new String[x];
while(scanner.hasNext()) { //while loop through the function
if(scanner.hasNextDouble()) {
setCoefficient(scanner.nextDouble()); //set the coefficient as the first double
}
setVariable(scanner.next()); //set the variable as the next function after first double
if(scanner.hasNextDouble()) {
setPower(scanner.nextDouble()); //set the exponent power as the next double
}
if(scanner.next() == "+") {
terms[x - 1] = "" + d.getCoefficient() + d.getVariable() + d.getPower(); //set the term into the array
x++; //make the array one slot bigger
}
}
}
public String[] differentiate(String analyzedFunction) {
String[] derivative = new String[terms.length];
for(int i = 0; i < terms.length; i++) {
double newCoefficient = d.getPower() * d.getCoefficient(); //exponent times coefficient
double newPower = d.getPower() - 1.0; //exponent power minus 1
derivative[i] = newCoefficient + d.getVariable() + " ^" + newPower;
if(i < terms.length)
derivative[i] = derivative + " + ";
}
return derivative[]; //HERE IS A PROBLEM
}
}
My compiler is telling me
"Syntax error on "[", expression expected after this token"
"Type mismatch: cannot convert from String to String[]"
Why am I not able to return the whole array? Eclipse's suggestion is change the return type to just a String, but I want to return a String array with each element being a differentiated term. How can I fix this?