This program is based upon the quadratic equation. If I enter a negative discriminant it prints NaN instead of "No real solutions". Any help will be appreciated. Why is it printing NaN twice??? What modifications are needed in the code? Please help!!!

import java.util.Scanner;
class QE{
private double d=0;
private double e=0;
private double f=0;
private double disc=0;
private double sol1=0;
private double sol2=0;
public QE(double a, double b, double c)
{d=a;e=b;f=c;
disc=e*e-4*d*f;
}

public boolean hasSolutions(){
return d<0;
}
public double getSolution1()
{sol1=(-e-Math.sqrt(disc))/2*d;
return sol1;
}
public double getSolution2()
{sol2=(-e+Math.sqrt(disc))/2*d;
return sol2;
}


}
public class QuadraticEquation {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter value of 'a':");
double a=in.nextDouble();
System.out.println("Enter value of 'b':");
double b=in.nextDouble();
System.out.println("Enter value of 'c':");
double c=in.nextDouble();
QE qd=new QE(a,b,c);
if(qd.hasSolutions())
System.out.println("No real solutions");
else if(qd.getSolution1()==0 && qd.getSolution2()==0)
System.out.println(0+" No solutions exist");
else
{System.out.println(qd.getSolution1());
System.out.println(qd.getSolution2());
}
}
}
Member Avatar for ztini

Oy, so many public methods...maybe something like this:

import java.util.Scanner;

public class QuadraticEquation {
	
	private double a, b, c;
	
	public QuadraticEquation() {
		getUserInput();
		printSolution();
	}
	
	private void getUserInput() {
		Scanner in = new Scanner(System.in);
		System.out.println("ax^2 + bx + c = x");
		System.out.println();
		System.out.print("a = ");
		a = in.nextDouble();
		System.out.print("b = ");
		b = in.nextDouble();
		System.out.print("c = ");
		c = in.nextDouble();
		System.out.println();
	}
	
	private double solve(int i) {
		return ((b * -1) + (i * (Math.sqrt((Math.pow(b, 2)) - (4 * a * c))))) / (2 * a);
	}
	
	private void printSolution() {
		System.out.print("x = ");
		if (!Double.isNaN(solve(1)))
			System.out.print("(" + solve(-1) + ", " + solve(1) + ")");
		else
			System.out.print("No Real Solution.");
	}
	
	public static void main(String[] args) {
		new QuadraticEquation();
	}
}

FYI, this thread has already been marked solved, so I can only assume he had already figured out the answer (or had cross-posted on other forums so that we would waste our time answering), but the OP should have the decency to post the answer (not necessarily the "new" code involved, a description would be enough) so that others with the same problem would need to ask the same question.

in line 15 of my code by mistake i typed d<0 intead of disc<0. Make it disc<0. The program works perfectly by changing it....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.