I'm hoping to get some feedback on how to improve and optimise a program I wrote which takes three values as input (via the terminal) and uses them in the quadratic formula.
I'm aware this is mostly micro-optimisation, but any advice whatsoever would be much appreciated.
public class Quadratic_Equations {
static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Please enter a, b and c or enter -1 at any time to exit");
double a = tryParse(sc.nextLine());
a = checkIfValidNumber(a);
if (a == -1)
break;
double b = tryParse(sc.nextLine());
b = checkIfValidNumber(b);
if (b == -1)
break;
double c = tryParse(sc.nextLine());
c = checkIfValidNumber(c);
if (c == -1)
break;
System.out.println(useQuadraticFormula(a, b, c));
System.out.println();
}
sc.close();
}
private static double checkIfValidNumber(double number) {
while (number == -1.0) {
System.out.println("You didn't enter a valid number for a. Please try again.");
number = tryParse(sc.nextLine());
}
return number;
}
public static Double tryParse(String text) {
try {
return new Double(text);
} catch (NumberFormatException e) {
return -1.0;
}
}
public static String useQuadraticFormula(double a, double b, double c) {
double result1;
double result2;
if (Math.pow(b, 2) - (4 * a * c) <= 0)
return "These numbers do not compute - they produce an illegal result.";
result1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
result2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return String.valueOf(result1) + ", " + String.valueOf(result2);
}
}
Among the things I really dislike are:
- The static
scanner
object. - The three different checks for -1 being entered.
- The quadratic formula method, which seems like it could be shortened.
I'm still working on this myself, but as I said any advice (including on naming conventions, code style etc.) would be appreciated.