Working with Functions
1 Introduction
On this lab, you will practice creating functions and separating single tasks on them, instead of having all the functionality in the main method. This helps not only when developing your code (because you think on resolving one small task at a time), but also when debugging errors (e.g., the copyright statement in the output is incomplete, so you go to the method that is responsible for printing it and fix it, instead of trying to figure out where it is in a 1 million line program), and making future improvements into your programs.
2 The Quadratic Equation Solver
Quadratic equations are very common in many professional fields, such as in mechanics, physics, and science in general. The trajectory of the angry bird game is represented by a quadratic equation. A quadratic equation is of the form:
y = ax2 + bx + c
Example:
y = 2x2 + 5x – 3
What engineers are looking for are the values of x that would give y=0. In the above example, if you replace x with 0.5 and do the hand calculation of that equation you would get y=0, i.e.,
y = 2*(0.5)2 + 5*0.5 – 3 = 0
A second number would also give y=0, x=-3.
So, the equation coefficients in this case are 2, 5, and -3 and the solutions (aka roots) are 0.5 and -3. Some quadratic equations have 2 solutions, or 1 solution, or no solution, depending on the coefficient values.
3 The Original Program
The program shown in Attachment A is a quadratic equation solver created by a student that did not know about methods. Create a new project in NetBeans and copy and paste this program there and run in with the following inputs and check if it is running ok before you go the next phase of this lab.
Case Number | Coefficients | Solutions |
1 | 2, 5,-3 | 0.5, 3.0 |
2 | 1, 2, 1 | -1 |
3 | 1, 2, 2 | no roots |
4 | 1, 2, “one” | Prints invalid input |
5 | 2, 5 | Prints invalid input |
4 The same program using Methods
Your task is to create methods that will do one single task each of them: a method to get the user input, a method to check input validity, a method to compute the solution, etc. Besides creating the method headers, most of your work will be to move existing lines from the original program into those methods. There are very, very few lines of code that you must create yourself (most of them are the methods headers and returning statements at the end of each method).
Attachment B has the main program for your modified program. It should give you all the necessary hints on your methods names, inputs and outputs. DO NOT CHANGE ANYTHING THAT IS IN RED. You must create your methods so that what I wrote there works with your methods.
Attachment A – Original Code
public class QuadraticEquationSolverWithoutMethods {
public static void main(String[] args) {
new QuadraticEquationSolverWithoutMethods();
}
public QuadraticEquationSolverWithoutMethods() {
// Step #1: getting coefficients from the user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter all the coefficients separated by comma: ");
String coefficientsInStringFormat = keyboard.nextLine();
String[] listOfCoefString = coefficientsInStringFormat.split(",");
// Step #2: validating inputs. Two things must be checked:
// a) If all the inputs are numbers (no string is allowed here)
// b) if there are exactly 3 numbers, corresponding to the quadratic coefficients
// validation (a): there must be 3 coefficients a, b, c
boolean validationCheck1 = listOfCoefString.length == 3;
// validation 2: all the inputs must be numbers (not letters or words)
boolean validationCheck2 = true;
try {
for (String coefStr : listOfCoefString) {
// trying to parse the picture of the number into a double.
// if not a number, this action will generate the Exception and
// we catch it and set the validationCheck2 to false, meaning
// it is not a number
double value = Double.parseDouble(coefStr.trim());
}
} catch (Exception e) {
validationCheck2 = false;
}
boolean inputIsValid = validationCheck1 && validationCheck2;
if (!inputIsValid) {
System.out.println("Invalid input! It must be three double numbers separated by comma.");
System.out.println("Example: 2, 5, -3");
System.exit(1);
}
// Step #3: converting the pictures of the numbers into actual numbers
double[] coefficients = new double[3];
for (int index = 0; index < 3; index++) {
coefficients[index] = Double.parseDouble(listOfCoefString[index].trim());
}
// step #4: computing the discriminant, discriminant = b^2 - 4ac
double discriminant = Math.pow(coefficients[1], 2) - 4 * coefficients[0] * coefficients[2];
// step #5: computing the solutions (roots) of the quadratic equation
double[] roots = new double[2];
int numberOfRoots = 0;
if (discriminant < 0) {
// no roots, do nothing here
} else if (discriminant == 0) { //Can someone remind me to talk about tolerance in class please!!!!
// one root: -b / 2a
roots[0] = -coefficients[1] / (2 * coefficients[0]);
numberOfRoots = 1;
} else {
roots[0] = (-coefficients[1] + Math.sqrt(discriminant)) / (2 * coefficients[0]);
roots[1] = (-coefficients[1] - Math.sqrt(discriminant)) / (2 * coefficients[0]);
numberOfRoots = 2;
}
// step #6: displaying results
switch (numberOfRoots) {
case 0:
System.out.println("no roots");
break;
case 1:
System.out.println("One real root");
System.out.println("root: " + roots[0]);
break;
case 2:
System.out.println("Two real roots");
System.out.println("root #1: " + roots[0]);
System.out.println("root #2: " + roots[1]);
break;
}
}
}
Attachment B – The Updated Program
public class QuadraticEquationSolverWithMethodss {
public static void main(String[] args) {
new QuadraticEquationSolverWithMethodss();
}
public QuadraticEquationSolverWithMethodss() {
// getting the coefficients in string format
String[] coefInStringFormat = getCoefficientsFromUserInput();
// validate inputs
if (areInputsValid(coefInStringFormat)) {
double[] coeffs = getConvertedCoefficients(coefInStringFormat);
double disc = computeDiscriminant(coeffs);
double[] roots = computeRoots(disc, coeffs);
displayResults(roots);
} else {
System.out.println("Invalid Input, please try again");
}
}
// your methods down here…
}