Results 1 to 3 of 3

# Thread: Take a derivative

- 05-02-2009, 10:17 PM #1Member
- Join Date
- Feb 2009
- Posts
- 47

- Rep Power
- 0

## Take a derivative

I want to take and display the derivative of a given input.

Java Code:import java.util.Scanner; public class Derivative { private int power; private int coefficient; private String variable; public static void main(String args[]) { Derivative d = new Derivative(); System.out.println(d.getDerivative(args[0])); //LINE 10 } public void setPower(int power) { this.power = power; } public int getPower() { return power; } public void setCoefficient(int coefficient) { this.coefficient = coefficient; } public int getCoefficient() { return coefficient; } public void setVariable(String variable) { this.variable = variable; } public String getVariable() { return variable; } public String getDerivative(String term) { String derivative; Scanner scanner = new Scanner(term); //pass the term to the scanner if(scanner.hasNextInt()) setCoefficient(scanner.nextInt()); //set the coefficient as the first integer setVariable(scanner.next()); //set the variable as the next term after first integer if(scanner.hasNextInt()) setPower(scanner.nextInt()); //set the exponent power as the next integer int newCoefficient = power * coefficient; //differentiate int newPower = power - 1; derivative = newCoefficient + variable + "^" + newPower; return derivative; } }

as a result. Whenever I call a hasNext... method with scanner, does the scanner move up a token? So that whenever I check, it moves, then I assign, and it moves, and I assign and check and etc etc. I feel like I'm doing something obviously wrong with the scanner, but I don't know how to fix it.

I also tried

Java Code:public String getDerivative(String term) { String derivative; Scanner scanner = new Scanner(term); //pass the term to the scanner setCoefficient(scanner.nextInt()); //set the coefficient as the first integer setVariable(scanner.next()); //set the variable as the next term after first integer setPower(scanner.nextInt()); //set the exponent power as the next integer int newCoefficient = power * coefficient; //differentiate int newPower = power - 1; derivative = newCoefficient + variable + "^" + newPower; return derivative; }

- 05-02-2009, 10:45 PM #2
You haven't configured the delimiters on your scanner. With default setup, your string has one token, '2x2', which cannot be parsed as an integer. hasNextInt() will return false, next() will return the whole token and the results will be as you see them.

Don't forget to mark threads as [SOLVED] and give reps to helpful posts.

How To Ask Questions The Smart Way

- 05-03-2009, 04:32 AM #3Member
- Join Date
- Feb 2009
- Posts
- 47

- Rep Power
- 0

## Bookmarks