Personal tools
You are here: Home Comp 170 Introduction to OOP Lab Materials Lab14 Solution
Document Actions

Solution

by Mit Patel last modified 2006-04-27 03:26 PM

Simple yet powerful solution

Click here to get the file

Size 1.7 kB - File type text/java

File contents

import java.util.Scanner; 
 
public class Quadratic 
{ 
   //----------------------------------------------------------------- 
   //  Determines the roots of a quadratic equation. 
   //----------------------------------------------------------------- 
   public static void main (String[] args) 
   { 
      int a, b, c;  // ax^2 + bx + c
  
      double discriminant, root1, root2; 
      boolean restart;
      
      Scanner scan = new Scanner (System.in); 

do {      
      System.out.print ("Enter the coefficient of x squared: "); 
      a = scan.nextInt(); 
 
      System.out.print ("Enter the coefficient of x: "); 
      b = scan.nextInt(); 
 
      System.out.print ("Enter the constant: "); 
      c = scan.nextInt(); 
    try {
      // Use the quadratic formula to compute the roots. 
      // Assumes a positive discriminant. 
     if (a == 0){
         throw new IllegalArgumentException("a can't be zero");
     }//end of if
     else { 
      discriminant = Math.pow(b, 2) - (4 * a * c); 
    
      if (discriminant < 0)
        throw new IllegalArgumentException("Discrimant < zero");
      root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); 
      root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); 
 
      System.out.println ("Root #1: " + root1); 
      System.out.println ("Root #2: " + root2); 
    
      
    }//end of else
}//end of try

 catch (IllegalArgumentException e){
    System.out.println("No solution");
    System.out.println(e.getMessage());
    
 }
  
      System.out.println();
      System.out.println("True to continue and False to exit");
      restart = scan.nextBoolean();
  } while(restart);
    
   
    
    } //end of main
} //end of class
« November 2023 »
Su Mo Tu We Th Fr Sa
1234
567891011
12131415161718
19202122232425
2627282930
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: