Today we started a practical exercise in class that we will continue to build on this week. This one provides two solutions for a quadratic equation using the quadratic formula.
Note: Some of this may note look nice and neat in the blog window, but if you copy it into JCreator, it should be much easier to read.
import java.util.Scanner;
public class QuadraticCalc {
public QuadraticCalc() {
}
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("This will find the possible answers for the Quadratic Formula given a, b and c.\n\n");
int a = 0; // These need to be initialize or the compiler will complain.
int b = 0;
int c = 0;
if (args.length == 3) { // If they gave values when they ran the program, use them. In Browxy this is done
// by entering them in the Arguments box. (Try "3 -10 5".)
// Otherwise, prompt for values.
a = Integer.parseInt(args[0]); // Keep in mind that 'args' is an array, and the first value in an array has an index of 0.
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);
}
else {
try {
System.out.print("Enter value of A: ");
a = input.nextInt(); // If you enter a non-numeric value, it will throw an exception.
System.out.print("Enter value of B: ");
b = input.nextInt(); // Same as above
System.out.print("Enter value of C: ");
c = input.nextInt();
}
catch (Exception e) {
System.out.println("Exception thrown in try..catch block.");
}
}
System.out.println("\nPossible solutions are: ");
System.out.println(" x = " + QuadFormula(a, b, c, Operator.Addition));
System.out.println(" x = " + QuadFormula(a, b, c, Operator.Subtraction));
}
public static double QuadFormula(int a, int b, int c, Operator op) { // Note the change I made to the signature.
// Operator is defined further down.
double answer = 0;
if (op == Operator.Addition) {
answer = (b * -1) + Math.sqrt(Math.pow(b, 2) - (4 * a * c));
}
else if (op == Operator.Subtraction) {
answer = (b * -1) - Math.sqrt(Math.pow(b, 2) - (4 * a * c));
}
answer = answer / (2 * a);
return answer;
}
public enum Operator { // Now, we're just having fun. Are you familiar with enumerators?
Addition,
Subtraction
}
}
No comments:
Post a Comment