Posted by: divdude July 18, 2007
any java programmers here in sajha?
Login in to Rate this Post:     0       ?        
import java.util.Scanner; import java.io.*; public class quadraticEquation{ public static void main(String[] args){ Scanner Keyboard = new Scanner(System.in); String inputString=args[0]; double[] values=parseInputString(inputString); double a, b, c, discriminant, rootA, rootB; a = values[0]; b = values[1]; c = values[2]; discriminant = (Math.pow(b, 2)) - (4*a*c); if(discriminant == 0.0) { rootA = (-b + Math.sqrt(discriminant)) / (2 *a); System.out.println("There is one root and the value of the root is: " + rootA); } else { if(discriminant > 0.0) { rootA = (-b + Math.sqrt(discriminant)) / (2 * a); rootB = (-b - Math.sqrt(discriminant)) / (2 * a); System.out.println("There are two real roots and the value of the roots are:"+ rootA + rootB); } else { if(discriminant < 0.0) { rootA = (-b + Math.sqrt(-discriminant)) / (2 * a); rootB = (-b + Math.sqrt(-discriminant)) / (2 * a); System.out.println("There are two imaginary roots and the value of the roots are: " + rootA + rootB); } } } System.exit(0); } public static double[] parseInputString(String inputString){ double[] d=new double[3]; int sign=1; int pos1=inputString.indexOf("x*2"); int pos2=inputString.length(); String a=inputString.substring(0,pos1); d[0]=Double.parseDouble(a); inputString=inputString.substring(pos1+3,pos2).trim(); if(inputString.charAt(0)=='-') sign=-1; else sign=1; pos1=inputString.indexOf("x"); String b=inputString.substring(1,pos1); d[1]=Double.parseDouble(b)*sign; pos2=inputString.length(); inputString=inputString.substring(pos1+1,pos2).trim(); if(inputString.charAt(0)=='-') sign=-1; else sign=1; pos2=inputString.length(); String c=inputString.substring(1,pos2); d[2]=Double.parseDouble(c)*sign; return d; } } It is basically same program but it takes input in the form of ax*2+bx+c as a command line parameter. To run excecute , compile and run as java quadraticEquation 2x*2-4x+1 and son on. you can have spaces as well if you like.
Read Full Discussion Thread for this article