Concept
How does the Java quadratic roots program check errors and calculate its roots?
ComputerScienceOne / Quadratic Roots Revisited
"/**\n\n* This program computes the roots to a quadratic equation\n\n* using the quadratic formula.\n\n*/\n\npublic class Roots {\n\npublic static void main(String args[]) {\n\ndouble a, b, c, root1, root2;\n\nif(args.length != 3) {\n\nSystem.err.println(\"Usage: a b c\n\n\");\n\nSystem.exit(1);\n\n}\n\na = Double.parseDouble(args[0]);\n\nb = Double.parseDouble(args[1]);\n\nc = Double.parseDouble(args[2]);\n\nif(a == 0) {\n\nSystem.err.println(\"Error: a cannot be zero\");\n\nSystem.exit(1);\n\n} else if(b*b < 4*a*c) {\n\nSystem.err.println(\"Error: cannot handle complex roots\n\n\");\n\nSystem.exit(1);\n\n} else if(b*b == 4*a*c) {\n\nroot1 = -b / (2*a);\n\nSystem.out.printf(\"Only one distinct root: %f\n\n\", root1);\n\n} else {\n\nroot1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a);\n\nroot2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a);\n\nSystem.out.printf(\"The roots of %fx^2 + %fx + %f are:\n\n\", a, b, c);\n\nSystem.out.printf(\" root1 = %f\n\n\", root1);\n\nSystem.out.printf(\" root2 = %f\n\n\", root2);\n\n}\n\n}\n\n}\n\nCode Sample 27.4.: Quadratic Roots Program in Java With Error Checking"
Related Ideas
- How can conditionals handle invalid inputs and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- How can conditionals handle invalid and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited
- How can a C program compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots
- What kinds of user input can cause problems in a quadratic-roots program?ComputerScienceOne · Computing Quadratic Roots
- How can quadratic-equation inputs be provided as command-line arguments?ComputerScienceOne · Computing Quadratic Roots
- How are command line arguments accessed and converted in Java?ComputerScienceOne · The javamain() Method
- What is 26?ComputerScienceOne · Computing Quadratic Roots
- How can a quadratic roots function return error codes?ComputerScienceOne · Error Handling By Design