//  Scott DeRuiter      7/3/2002
//  Quad.java
//  Finds the roots to a quadratic function, if they exist
//  7/15/2011 - Greenstein: Changed TextReader to Scanner

import java.util.Scanner;

public class Quad   
{

	private double A, B, C, root1, root2;

	public Quad ( )   
	{
		A = B = C = root1 = root2 = 0.0;
	}

	public static void main ( String [] args )   
	{
		Quad q = new Quad ( );

		q.GetInput ( );
		q.CalculateAndPrintOutput ( );
	}

	public void GetInput ( )   
	{
		Scanner keyboard = new Scanner ( System.in );

		System.out.print ( "\n\nEnter the value for A    -> " );
		A = keyboard.nextDouble ( );
		System.out.print ( "Enter the value for B    -> " );
		B = keyboard.nextDouble ( );
		System.out.print ( "Enter the value for C    -> " );
		C = keyboard.nextDouble ( );
	}

	public void CalculateAndPrintOutput ( )   
	{
		if ( A == 0.0 )   
		{
			if ( B == 0.0 )
				System.out.println ( "\n\nNo Roots" );
			else  
			{
				root1 = -C / B;
				System.out.println ( "\n\nOne root:  " + Format.right ( root1, 10, 3 ) );
			}
		}
		else   
		{
			double disc = B * B - 4 * A * C;
			if ( disc <= 0.00000001 && disc >= -0.00000001 )   
			{
				root1 = ( -B ) / ( 2 * A );
				System.out.println ( "\n\nOne root:   " + Format.right ( root1, 10, 3 ) );
			}
			else if ( disc > 0 )  
			{
				root1 = ( -B + Math.sqrt ( disc ) ) / ( 2 * A );
				root2 = ( -B - Math.sqrt ( disc ) ) / ( 2 * A );
				System.out.println ( "\n\nFirst root:   " + Format.right ( root1, 10, 3 ) );
				System.out.println ( "\nSecond root:  " + Format.right ( root2, 10, 3 ) );
			}
			else
				System.out.println ( "\n\nNo Real Roots" );
		}
	}
}

Back to Lesson 6 Examples

Back to Java Main Page