1

My professor wants me to write an object oriented program with Java, that solves some quadratic equation as many times as args[0] is defined, for example computer-:Desktop User$ java program_name 3 will iterate the programs 3 times.(I hope that's clear enough).

I have everything down, except the "object oriented program", I don't see how I can make it object oriented, the instructions don't leave me too much room to work (other than with a constructor method).

I've been trying to do this:

public class assignment {
assignment(double method_inp){
    double coeff = method_inp;
}
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int input_number = Integer.parseInt(args[0]);

    if (input_number > 0) {
        for (int i = 0; i < input_number; i++) {

            // isn't this object oriented?
            assignment a = new assignment(readCoeff(input));
            assignment b = new assignment(readCoeff(input));
            assignment c = new assignment(readCoeff(input)); 

(readCoeff(input) just goes to scanner and lets the user input the value. but it seems I can't use a, b and c as variables. nor convert them to variables, because they can't be converted to double. What can I do? is there a better way to make my program object oriented?

Edit: I can't use global variables

Edit: Content of readCoeff(input) is:

static double readCoeff(Scanner inn) {
    System.out.print("Please enter coefficient of a quadratic equation: ");
    return inn.nextDouble();
1
  • what is the content of readCoeff? Commented Sep 19, 2015 at 20:22

4 Answers 4

3

Any time you use the word static you are "generally" not in an OOP model.

why?

Because static lifts state (in a design sense) from a object context to a module context. All your programming is happening inside a static method (with the exception of the solver).

Here is what I like to do

public class Program
{
  public static void main(String[] args) {
     Parser p = new MyCommandlineParser();
     Options op = p.Parse(args);

     Solver solver = new Solver();
     s.SolveVariables(op.getTimesToSolve());
     System.out.println("Done.  OOP is about design not programming");
  }
}

start with design then program;

Sign up to request clarification or add additional context in comments.

4 Comments

Well, there's already a Parser: java.util.Scanner. And yeah, your solution is fully object-oriented, but no need to act like Java is Smalltalk, it's an overkill for such a simple task imho.
OOP or as I prefer to call it (OOD) is all about design. If the prof (or in business the customer) ends up building on this program it will be easier to extend if you build it in such a way that its easily extensible; you should wrap the command line parsing in its own class so if you start parsing more args, that logic is already encapsulated. also your ivory tower prof will love the level of encapsulation.
okay, can't argue with that. If OP is ever to build a professional quadratic equation solver operating fully from the command line, that's the way to go
@leat I've had to do more research to understand this answer that all of my other programming exercises combined. (I am in an intro to Java class, and we just learned how to use loops, so I am very noob...in paper anyway, I am actually more advanced than that) Still I thank you so much for your answer, I never saw OOP as OOD, but that makes a lot of sense, I will keep it in mind as I move forward in my education.
1

Represent your Equations (Quadratic) using a separate class. Define the operation definition in the class, Which you want to perform on the operation. These operations will be accessed using the instance of the Equation.

The main class assignment will accept the number of equations and create the instance in a array of equations.

import java.util.Scanner;

class Equation {
  double a, b, c;
  Equation(double a, double b, double c) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
  // Perform the operation on equation using specific methods.
}

public class assignment {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int input_number = Integer.parseInt(args[0]);
    Equation objects[];
    double inputA, inputB, inputC;
    if (input_number > 0) {
      objects = new Equation[input_number];
      for (int i = 0; i < input_number; i++) {
        inputA = readCoeff(input);
        inputB = readCoeff(input);
        inputC= readCoeff(input);
        objects[i] = new Equation(inputA, inputB, inputC);
      }
    }
  }
  static double readCoeff(Scanner inn) {
    System.out.print("Please enter coefficient of a quadratic equation: ");
    return inn.nextDouble();
  }
}

2 Comments

@Gaskoin Hey, did you look the updated answer I have posted. Also I would like to see your approach for the same. Please find some free time. Thanks.
now it's much better:) my approach will be very similar.
1
import java.util.Scanner;

/**
 * Created by EpicPandaForce on 2015.09.20..
 */
public class Main {
    public static void main(String[] args) {
        int iterationCount;
        if (args.length > 0) {
            iterationCount = Integer.parseInt(args[0]);
        } else {
            iterationCount = 1;
        }
        new Main().execute(iterationCount);
    }

    private Scanner scanner;

    public Main() {
        scanner = new Scanner(System.in);
    }

    public void askForCoefficientInput() {
        System.out.println("Please enter the three coefficients");
    }

    public double readCoefficient() {
        return scanner.nextDouble();
    }

    public void execute(int iterationCount) {
        double inputA, inputB, inputC;
        if (iterationCount > 0) {
            for (int i = 0; i < iterationCount; i++) {
                askForCoefficientInput();
                inputA = readCoefficient();
                inputB = readCoefficient();
                inputC = readCoefficient();
                Equation equation = new Equation(inputA, inputB, inputC);
                equation.printResults();
            }
        }
    }

    public static class Equation {
        private double a;
        private double b;
        private double c;

        private double result1;
        private double result2;
        private boolean hasResult;

        public Equation(double a, double b, double c) {
            this.a = a;
            this.b = b;
            this.c = c;
            calculate();
        }

        protected final void calculate() {
            if (a != 0) {
                if ((b * b - 4 * a * c) >= 0) {
                    this.result1 = ((-1) * b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
                    this.result2 = ((-1) * b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
                    this.hasResult = true;
                }
            } else {
                if (b != 0) {
                    this.result1 = ((-1) * c) / b;
                    this.result2 = ((-1) * c) / b;
                    this.hasResult = true;
                } else {
                    if (c == 0) {
                        this.result1 = 0;
                        this.result2 = 0;
                        this.hasResult = true;
                    }
                }
            }
        }

        public void printResults() {
            System.out.println(
                    "The equation [" + a + "x^2 " + (b >= 0 ? "+" + b : b) + "x " + (c >= 0 ? "+" + c : c) + "] had " + (this.hasResult() ? "" : "no ") + "results" + (this.hasResult() ? ", these are: [" + this
                            .getFirstResult() + "] and [" + this.getSecondResult() + "]." : "." + "\n"));
        }

        public double getFirstResult() {
            return this.result1;
        }

        public double getSecondResult() {
            return this.result2;
        }

        public boolean hasResult() {
            return this.hasResult;
        }
    }
}

Result:

>> Executing quadratic.Main

Please enter the three coefficients
1 -8 12
The equation [1.0x^2 -8.0x +12.0] had results, these are: [6.0] and [2.0].

Please enter the three coefficients
3 8 12
The equation [3.0x^2 +8.0x +12.0] had no results.

Process finished with exit code 0

3 Comments

Yes, it does not handle complex numbers.
This is great, but I can't use it because it has class variables.( thanx for posting it though, It actually explained a lot of questions I had.
I'm not sure how you're supposed to achieve encapsulation without using field variables... I'm glad it helped. Also, I think @leaf's answer is the clearest; every type of action has its own class which gives a clear set of responsibility to each class that is used. For example, in my case, the printResults() method doesn't really make sense for it to be part of an Equation, an Equation doesn't really have to know anything about Printing, and should be its own class that operates on an Equation. Alas, it's easy to refactor it that way, but to design top-down like that is a skill.
0

Doing something that can be done much more efficiently and cleanly without objects by forcing OOP is kinda retarded. But, there are teachers like that (I know a few as well). So, here's the way I'd do it:

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int inputNumber = Integer.parseInt(args[0]);

        if (inputNumber > 0) {
            for (int i = 0; i < inputNumber; i++) {
                int[] coefficients;
                //read coefficients into the array
                QuadraticEquation equation = new QuadraticEquation(coefficients);
                System.out.println(equation.solve());
            }
        }
    }
}


class QuadraticEquation {
    private int[] coefficients;

    QuadraticEquation(int[] coefficients) {
        this.coefficients = coefficients;
    }

    double solve() {
        //solve the equation using coefficients and return the result
    }
}

Replace variable/field names with something more sensible if needed. Also, class names should always be uppercase. Compiler won't complain, but it's a widely accepted convention.

Now, what actually happens in the above code is that we define a class named QuadraticEquation which is defined by it's coefficients and we pass them in constructor. Now, when the object has all the necessary information, we can call solve() on it to actually do something, i. e. give us the result, which we print out (you can also save all the results in an array and print them out at the end).

Also note that we have two classes. You can put everything into one, but I don't think you should. Every class should represent an Object that can work on its own (Main class is actually pointless when you look it from that angle; it's just there to prevent main(String[]) to pollute other stuff).

Ideally, you'd make a separate file named QuadraticEquation, change class QuadraticEquation to public class QuadraticEquation and prefix constructor and methods with public to make them usable from anywhere, because they aren't tied to anything specifically. I wanted to keep things simple and dumped everything into one place, and because you can't have two public classes in one file, the other one had to be package-protected (the default visibility level).

2 Comments

"Doing something that can be done much more efficiently and cleanly without objects by forcing OOP is kinda retarded. But, there are teachers like that (I know a few as well)." Nothing wrong with that. The purpose of the exercise is to test/practise the students' OOP skills, not to find the solutions to quadratic equations.
Yeah, but there are better exercises, e. g. something that includes data modelling. This one focuses solely on calculation, only model you have is an equation itself. You can make better use of it if you introduce complex numbers though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.