ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to solve a Quadratic Equation in Java ?.

Updated on December 16, 2017

In this Java tutorial, you will learn how to solve Quadratic equation through a Java program. In this Java tutorial, you will encounter a video tutorial which will demonstrate how to solve Quadratic equation step-by-step. Below there is complete Java source code along with steps to implement the same. At last there is output of the program.

What is a Quadratic Equation ?.

Video tutorial - How to solve Quadratic Equation in Java ?.

Below is the video tutorial, which demonstrate how to solve Quadratic Equation in Java step-by-step.

// Step 1 - Import Scanner class from the package
// java.util. Before using Scanner class nextDouble
// method, you have to import Scanner class.
import java.util.Scanner;

public class QuadraticEquationDemo
{
	public static void main(String[] args)
	{
		// Step 2 - Create a Scanner class instance using
		// new operator and calling Scanner constructor.
		// The constructor takes in System.in inputstream
		// as a parameter to it. System.in helps Scanner
		// class to read user inputs from the Java console.
		Scanner input = new Scanner(System.in);

		// Step 3 - Create 5 variables of datatype double.
		// These variables take in values of constants used in 
		// quadratic equation such as - a , b , c , d ,discriminant.
		// All these variables are initialized to zero. These variables
		// hold values entered by the user later.
		double a = 0;
		double b = 0;
		double c = 0;
		double d = 0;
		double discriminant = 0;

		// Step 4 - Prompt the user to enter the value of constant a.
		System.out.print("Enter the value of constant a : "); 

		// Step 5 - a holds the value entered by the user on Java console.
		// Scanner class has a method by name nextDouble(). This method
		// reads double value entered by user on the Java console and 
		// assign it to a variable.
		a = input.nextDouble();

		// Step 6 - Prompt the user to enter the value of constant b.
		System.out.print("Enter the value of constant b : "); 

		// Step 7 - b holds the value entered by the user on Java console.
		// Scanner class has a method by name nextDouble(). This method
		// reads double value entered by user on the Java console and 
		// assign it to b variable.
		b = input.nextDouble();

		// Step 8 - Prompt the user to enter the value of constant c.
		System.out.print("Enter the value of constant c : "); 

		// Step 9 - c holds the value entered by the user on Java console.
		// Scanner class has a method by name nextDouble(). This method
		// reads double value entered by user on the Java console and 
		// assign it to c variable.
		c = input.nextDouble();

		// Step 10 - Calculate discriminant of quadratic equation by using
		// following formula - 
		// discriminant = (b * b - 4 * a * c)
		discriminant = (b * b - 4 * a * c);

		// Step 11 - Calculate the value of d by using following formula - 
		// d = square root of discriminant.
		// Math class has a static method by name sqrt(). This method 
		// returns square root of number passed to it as parameter.
		d = Math.sqrt(discriminant);

		// Step 12 - Here, if discriminant comes out to be greater than 
		// quadratic equation has two roots calculated by formula - 
		// roots = + ( -b + d ) / ( 2.0 * a ))
		// else roots of quadratic equation are not real numbers.
		if (discriminant >= 0.0) {
			System.out.println("First root of the Quadratic equation is : "
					+(-b + d) / (2.0*a));

			System.out.println("Second root of the Quadratic equation is : "
					+(-b - d) / (2.0*a));
		} 
		else 
		{
			System.out.println("The roots are not real numbers.");
		}
	}
}

Steps to implement -

Step 1 - Import Scanner class from the package java.util. Before using Scanner class nextDouble method, you have to import Scanner class.

Step 2 - Create a Scanner class instance using new operator and calling Scanner constructor. The constructor takes in System.in inputstream as a parameter to it. System.in helps Scanner class to read user inputs from the Java console.

Step 3 - Create 5 variables of datatype double. These variables take in values of constants used in quadratic equation such as - a , b , c , d ,discriminant. All these variables are initialized to zero. These variables hold values entered by the user later.

Step 4 - Prompt the user to enter the value of constant a.

Step 5 - 'a' holds the value entered by the user on Java console. Scanner class has a method by name nextDouble(). This method reads double value entered by user on the Java console and assign it to 'a' variable.

Step 6 - Prompt the user to enter the value of constant b.

Step 7 - 'b' holds the value entered by the user on Java console. Scanner class has a method by name nextDouble(). This method reads double value entered by user on the Java console and assign it to 'b' variable.

Step 8 - Prompt the user to enter the value of constant c.

Step 9 - 'c' holds the value entered by the user on Java console. Scanner class has a method by name nextDouble(). This method reads double value entered by user on the Java console and assign it to 'c' variable.

Step 10 - Calculate discriminant of quadratic equation by using
following formula -
discriminant = (b * b - 4 * a * c)

Step 11 - Calculate the value of d by using following formula -
d = square root of discriminant.
Math class has a static method by name sqrt(). This method returns square root of number passed to it as parameter.

Step 12 - Here, if discriminant comes out to be greater than quadratic equation has two roots calculated by formula -
roots = + ( -b + d ) / ( 2.0 * a ))
else roots of quadratic equation are not real numbers.



Output of the program -

Output of the program when the value of the discriminant is greater than 0.

Therefore,

discriminant = (b * b - 4 * a * c) = 6 * 6 - 4 * 4 * 2 = 4, which is greater than 0.

Output of the program -

Output of the program when the value of the discriminant is equal to 0.

Therefore,

discriminant = (b * b - 4 * a * c) = 4 * 4 - 4 * 2 * 2 = 0, which is equal to 0.

Output of the program -

Output of the program when the value of the discriminant is less than 0.

Therefore,

discriminant = (b * b - 4 * a * c) = 4 * 4 - 4 * 10 * 2 = -64, which is less than 0.

Thanks for reading the tutorial. In case you find any difficulty in solving Quadratic Equation in Java, please write into comments. The video tutorial demonstrates step by step execution of the program.

© 2013 dinesh-varyani

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)