Question

This is my main class:

import java.util.Scanner;

public class calc {
public static void main(String[] args){
    Scanner variablea = new Scanner(System.in);
    Scanner variableb = new Scanner(System.in);
    Scanner variablec = new Scanner(System.in);
    int a1, b1, c1;
    System.out.println("enter your 'A' variable");
    a1 = variablea.nextInt();
    System.out.println("enter your 'B' variable");
    b1 = variableb.nextInt();
    System.out.println("enter your 'C' variable");
    c1 = variablec.nextInt();

    algorithm algorithmObject = new algorithm();
    algorithmObject.algorithm(a1, b1, c1);

}

}

and this is the second one

      public class algorithm{
public void algorithm(int a, int b, int c){
    double x1;
    double square = Math.sqrt(b*b - 4*a*c);
    double numerator = b*-1 + square;
    double finalanswer = numerator/2*a;

    System.out.println(finalanswer);
}

}

Eclipse doesn't give me any errors, but after it asks for my 3 variables and I enter them, it just gives NaN. Any idea what I have done wrong?

Was it helpful?

Solution

There are issues with the code but the culprit is most likely this line:

double square = Math.sqrt(b*b - 4*a*c);

If b*b - 4*a*c is negative (there is no solution to the equation) then square is NaN and every computation involving it will be NaN as well. You can check it here.


You could improve your calculator by first checking if b*b - 4*a*c < 0 and if it is so then you could write to the console that there is no real solution (and of course stop the computations there).


I would change public void algorithm(int a, int b, int c) to

public void algorithm(double a, double b, double c)

Integer arithmetic can surprise you when you least expect it and I see no reason why a, b and c should be constrained to be int-s.


OK, hope this helped.

OTHER TIPS

There are several special cases that you need to watch out for. You don't seem to watch for any of them:

y = a*x^2 + b*x + c
  1. If the quadratic coefficient a is zero, there's only one root because the equation is linear: y = b*x + c.
  2. If the linear coefficient b is zero, there are two roots: [x1, x2] = +/-sqrt(c)
  3. If the constant coefficient c is zero, one of the roots is zero and the other is -b/a.

If the discriminant is negative, you have two complex conjugate roots.

The interesting thing is that all these situations have meaning for the solutions of physics problems like damped harmonic motion and L-C-R circuits. You should learn something about those, too.

As this looks a bit a homework assignment, I'll only give a hint:

NaN is what math functions return when the result can not be accurately represented as a number for some reason, either technical or mathematical.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top