使用 java 编写 OOP

Writing an OOP with java

我的教授希望我用 Java 编写一个面向对象的程序,它可以根据定义的 args[0] 多次求解某个二次方程,例如 computer-:Desktop User$ java program_name 3 将迭代程序3 次。(我希望你说得够清楚了)。

除了 "object oriented program",我什么都没有了,我不知道如何让它成为面向对象的,这些说明没有给我太多的工作空间(除了使用构造方法).

我一直在尝试这样做:

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) 只是转到扫描仪并让用户输入值。 但似乎我不能使用 abc 作为变量。也不会将它们转换为变量,因为它们无法转换为双精度。我能做什么?有没有更好的方法让我的程序面向对象?

编辑:我不能使用全局变量

编辑:readCoeff(input) 的内容是:

static double readCoeff(Scanner inn) {
    System.out.print("Please enter coefficient of a quadratic equation: ");
    return inn.nextDouble();

使用单独的 class 表示您的 Equations(二次)。在class中定义操作定义,你要对哪个操作执行。将使用 Equation 的实例访问这些操作。

主要 class assignment 将接受方程的数量并在方程数组中创建实例。

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();
  }
}

只要你使用静态这个词,你就"generally"不在 OOP 模型中。

为什么?

因为静态将状态(在设计意义上)从对象上下文提升到模块上下文。您的所有编程都在静态方法中进行(求解器除外)。

这是我喜欢做的事情

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");
  }
}

先设计再编程;

通过强制 OOP 来做一些可以在没有对象的情况下更有效、更干净地完成的事情有点迟钝。但是,有这样的老师(我也认识一些)。所以,我会这样做:

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
    }
}

如果需要,用更合理的名称替换 variable/field 名称。此外,class 名称应始终为大写。编译器不会抱怨,但这是一个被广泛接受的惯例。

现在,上面代码中实际发生的是我们定义了一个名为 QuadraticEquation 的 class,它由它的系数定义,我们将它们传递给构造函数。现在,当对象拥有所有必要的信息时,我们可以调用 solve() 来实际做一些事情,即。 e.给我们结果,我们打印出来(你也可以将所有结果保存在一个数组中,最后打印出来)。

另请注意,我们有两个 classes。您可以 将所有内容合二为一,但我认为您不应该这样做。每个 class 应该代表一个可以独立工作的对象(从那个角度看,Main class 实际上是没有意义的;它只是为了防止 main(String[]) 污染其他的东西)。

理想情况下,您可以创建一个名为 QuadraticEquation 的单独文件,将 class QuadraticEquation 更改为 public class QuadraticEquation 并在构造函数和方法前加上 public 前缀,使它们可以在任何地方使用,因为它们没有特定地绑定到任何东西。我想保持简单并将所有内容都转储到一个地方,因为你不能在一个文件中有两个 public classes,另一个必须是包保护的(默认可见性级别).

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;
        }
    }
}

结果:

>> 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