Freddy1990
06-23-2007, 08:21 PM
I was bored, quickly wrote up this:
/**
* Quadratic equation solver
* @author Freddy1990
*
*/
public class Quadratic {
/**
* Main method to solve the equation.
* @param a The first value of the equation
* @param b The second value of the equation
* @param c The third value of the equation
*/
public Quadratic(int a, int b, int c) {
double D = Math.pow(b, 2) - 4 * a * c;
if (D < 0)
System.out.println("No solutions");
else if (D == 0) {
double x = -b / (2 * a);
System.out.println("Discriminant = " + String.valueOf(D));
System.out.println("One solution:");
System.out.println("x = " + String.valueOf(x));
} else {
double x1 = (-b + Math.sqrt(D)) / (2 * a);
double x2 = (-b - Math.sqrt(D)) / (2 * a);
System.out.println("Discriminant = " + String.valueOf(D));
System.out.println("Two solutions:");
System.out.println("x1 = " + String.valueOf(x1));
System.out.println("x2 = " + String.valueOf(x2));
}
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 3) {
int a = Integer.parseInt(args[0]);
if (a != 0) {
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
System.out.println("ax² + bx + c");
System.out.println("a = " + args[0] + " , b = " + args[1] + " , c = " + args[2]);
new Quadratic(a, b, c);
} else
System.out.println("The first value of a quadratic equation cannot be 0.");
} else {
System.out.println("Usage: value1 value2 value3");
}
}
}
You enter the values trough commandline, run it like this:
java Quadratic a b c
/**
* Quadratic equation solver
* @author Freddy1990
*
*/
public class Quadratic {
/**
* Main method to solve the equation.
* @param a The first value of the equation
* @param b The second value of the equation
* @param c The third value of the equation
*/
public Quadratic(int a, int b, int c) {
double D = Math.pow(b, 2) - 4 * a * c;
if (D < 0)
System.out.println("No solutions");
else if (D == 0) {
double x = -b / (2 * a);
System.out.println("Discriminant = " + String.valueOf(D));
System.out.println("One solution:");
System.out.println("x = " + String.valueOf(x));
} else {
double x1 = (-b + Math.sqrt(D)) / (2 * a);
double x2 = (-b - Math.sqrt(D)) / (2 * a);
System.out.println("Discriminant = " + String.valueOf(D));
System.out.println("Two solutions:");
System.out.println("x1 = " + String.valueOf(x1));
System.out.println("x2 = " + String.valueOf(x2));
}
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 3) {
int a = Integer.parseInt(args[0]);
if (a != 0) {
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
System.out.println("ax² + bx + c");
System.out.println("a = " + args[0] + " , b = " + args[1] + " , c = " + args[2]);
new Quadratic(a, b, c);
} else
System.out.println("The first value of a quadratic equation cannot be 0.");
} else {
System.out.println("Usage: value1 value2 value3");
}
}
}
You enter the values trough commandline, run it like this:
java Quadratic a b c