Advertisement
IvonLiu

Untitled

Jul 1st, 2015
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.text.DecimalFormat;
  3.  
  4. class quad {
  5. public static void main (String[] args) {
  6.  
  7. Scanner user_input = new Scanner(System.in);
  8.  
  9. Double a = getDouble(user_input, "Coefficient of x^2: ");
  10. Double b = getDouble(user_input, "Coefficient of x: ");
  11. Double c = getDouble(user_input, "Constant: ");
  12.  
  13. user_input.close(); // We are done with the scanner now.
  14.  
  15. Double x1 = (-b + Math.sqrt(b*b-4*a*c))/(2*a);
  16. Double x2 = (-b - Math.sqrt(b*b-4*a*c))/(2*a);
  17.  
  18. DecimalFormat fmt = new DecimalFormat("+ #.#####;- #.#####");
  19.  
  20. if (Double.isNaN(x1)) {
  21. original(a, b, c);
  22. System.out.println(" does not cross the x axis");
  23. System.out.println("There are no real values for x");
  24. } else if (x1.equals(x2)) {
  25. original(a, b, c);
  26. System.out.println(" = (x " + fmt.format(-x1) + ")^2");
  27. System.out.println("X is " + x1);
  28. } else {
  29. original(a, b, c);
  30. System.out.println(" = (x " + fmt.format(-x1) + ")(x " + fmt.format(-x2) + ")");
  31. System.out.println("X can be " + x1 + " or " + x2);
  32. }
  33. }
  34.  
  35. public static double getDouble (Scanner scanner, String prompt) {
  36. double input = 777.7; //value will be parsed again
  37. boolean errorAlert = false;
  38. while(!errorAlert) {
  39. errorAlert = true;
  40. try {
  41. System.out.print(prompt);
  42. input = Double.parseDouble(scanner.next());
  43. } catch (NumberFormatException e) {
  44. System.out.println("Input must be a decimal number.");
  45. errorAlert = false;
  46. }
  47. }
  48. return input;
  49. }
  50.  
  51. public static void original (double a, double b, double c) {
  52. System.out.print(a + "x^2 + " + b + "x + " + c);
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement