user6798179
user6798179

Reputation:

Beginner difficulties writing completing the square in Java

I am a beginner in the world of Java and I have been assigned to write out code to ask for coefficients and then complete the square. I have been at it for several hours researching what to do with no avail (again, beginner) and any help would be appreciated.

    import java.util.Scanner;

    // Declare class
    public class Squares
 {
        // Main method of class. Execution starts
        public static void main(String[] args)
    {
    // Declare variables
    double a, b, c;
    char x = 'x';

    // Print name
    System.out.println("Program 2 (Complete the Square) by <your name> \n");

    // Create scanner
    Scanner scan = new Scanner(System.in);

    // Print prompt for variable a
    System.out.println("Enter value for a, a=");
    // Set a to input value
    a = Double.parseDouble(scan.nextLine());

    System.out.println("Enter value for b, b=");
    b = Double.parseDouble(scan.nextLine());

    System.out.println("Enter value for c, c=");
    c = Double.parseDouble(scan.nextLine());

    System.out.println(a*Math.pow(x, 2)+b*x+c=0);
    }
 }

This is the error I receive

    c:\cs\program2>javac Squares.java
    Squares.java:41: error: unexpected type
            System.out.println(a*Math.pow(x, 2)+b*x+c=0);
                                                   ^
      required: variable
      found:    value
      1 error

The desired output is given by this example

    > java Program2
    Program 2 (Complete the Square) by <your name>
    Enter a: 1
    Enter b: 2
    Enter c: 0
    01.0*x^2 + 2.0*x + 0.0 = 0
    01.0*(x + 1.0)^2 – 1.0 = 0

Upvotes: 0

Views: 655

Answers (1)

Timothy Murphy
Timothy Murphy

Reputation: 1362

So, completing the square is often used to find ways to find the value of x-intercepts for quadratic equations.

Assuming you have three coefficients, a, b, c s.t. ax^2 + bx + c = 0. You want to find what values x can take to make the above equation true.

One way to do this is to use the quadratic equation, but instead you wish to use completing the square method.

You want a way to go from ax^2 + bx + c = 0 to (x + m)^2 = n and it'd be easy to find that x = -m + sqrt(n) or x = -m - sqrt(n).

Before I give any code, I'll give you the steps to do this on paper.

For any quantity (x + a)^2 = x^2 + 2ax + a^2 which will be useful for this method.

Assuming your given: a, b, c

Step 1: normalize coefficients so that a = 1 (divide a,b,c by a) This step works because ax^2 + bx + c = 0 is equivalent to x^2 + (b/a)x + c/a = 0.

Step 2: move the normalized c to the other side of the equation. x^2 + bx = -c

Step 3: add (b/2)^2 to both sides of the equation x^2 + bx + (b/2)^2 = -c + (b/2)^2

Step 4: rewrite left side (as a square) (x + b/2)^2 = -c + (b/2)^2

Step 5: Solve for x x = -b/2 +/- sqrt(-c + (b/2)^2)

Now the code: The first section actually finds values for x if any real-valued intercepts exist.

public static void complete_square(double a, double b, double c) {
  b /= a;
  c /= a;
  c *= -1;
  c += (b/2)*(b/2);
  if (c < 0){
    System.err.println("Error: no real valued roots");
    return;
  }
  if (c == 0){
    System.out.format("X = %f", -b/2); // solution (only 1 distinct root)
    return;
  }
  System.out.format("X = %f", -b/2 + sqrt(c)); // solution 1
  System.out.format("X = %f", -b/2 - sqrt(c)); // solution 2
}

Edit: Updates output to requested format and gives more complete skeleton of code.

import java.util.Scanner;
import Java.lang.Math;

public class Squares {
  public static void main(String args[]){
    // Do your header output and input to get a,b,c values

    // Print the input equation. Uses format to "pretty print" the answer
    // %s - expects a string and %c expects a character
    System.out.format("%s*x^2 %c %s*x %c %s = 0\n",
                      Double.toString(a),
                      (b < 0 ? '-' : '+'),  // ternary operator. Select '-' if b is negative and '+' if b is positive
                      Double.toString(Math.abs(b)),
                      (c < 0 ? '-' : '+'),
                      Double.toString(Math.abs(c)));
    complete_square(a, b, c);
  }

  public static void complete_square(double a, double b, double c) {
    b /= a;
    c /= a;
    a /= a;
    c -= (b/2)*(b/2);
    System.out.format("%s*(x %c %s)^2 %c %s = 0",
                      Double.toString(a),
                      (b < 0 ? '-' : '+'),
                      Double.toString(Math.abs(b/2)),
                      (c < 0 ? '-' : '+'),
                      Double.toString(Math.abs(c)));
  }
}

Note: I highly suggest you try to understand the math behind this code before just copy and pasting the above code.

Upvotes: 2

Related Questions