After taking some great advice on this question this question, I'm hoping for some more feedback on my quadratic expression calculator.
After taking some great advice on this question, I'm hoping for some more feedback on my quadratic expression calculator.
After taking some great advice on this question, I'm hoping for some more feedback on my quadratic expression calculator.
Quadratic Expression Calculator 2
After taking some great advice on this question, I'm hoping for some more feedback on my quadratic expression calculator.
This is my code as stands:
public class Quadratic_Equations {
private final 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 \"exit\" at any time to exit");
double a = promptUserUntilValidInput("Please enter a:");
double b = promptUserUntilValidInput("Please enter b:");
double c = promptUserUntilValidInput("Please enter c:");
System.out.println(formatOutput(calculateQuadraticFormula(a, b, c)));
System.out.println();
}
}
private static String formatOutput(Set<Double> resultsFromEquation) {
if (resultsFromEquation == null)
return "These numbers do not compute - they produce an illegal result.";
else {
return resultsFromEquation.toString();
}
}
private static double promptUserUntilValidInput(String prompt){
if (prompt.equals("exit")) {
sc.close();
System.exit(0);
}
boolean valid = false;
Double value = new Double(0.0);
while(!valid){
System.out.println(prompt);
value = tryParse(sc.nextLine());
if (value != null)
valid = true;
}
return value;
}
private static Double tryParse(String text){
try{
return Double.parseDouble(text);
}
catch (NumberFormatException e){
return null;
}
}
public static Set<Double> calculateQuadraticFormula(double a, double b, double c) {
Set<Double> results = new HashSet<Double>();
double temp = (b * b) - (4 * a * c);
if (temp < 0)
return null;
if( temp == 0 ) {
results.add(-b / 2 * a);}
else if( temp > 0) {
results.add( (-b + Math.sqrt(temp) ) / (2 * a) );
results.add( (-b - Math.sqrt(temp) ) / (2 * a) );
}
return results;
}
}
Before I go on, there are a few things I should point out.
I'm aware this could be better if the quadratic stuff was in a class of its own - however, for the purposes of this simple exercise I'm happy skipping that.
My main issues are:
static Scanner. Some people on previous question suggested making this a private variable, but then it needs to get passed to everything. Is this worth it?
Does it look okay to close the scanner (and exit the program) where I do?
Do other methods look single-responsibility-ish enough?