【问题标题】:Constructor doesn't initialize proper values [duplicate]构造函数没有初始化正确的值[重复]
【发布时间】:2019-03-10 06:58:07
【问题描述】:

我是 Java 新手,在下面附加的代码中,我有 2 个类,Start.java 和 ecuație.java。 ecuatie.java 计算二次方程的平方英尺,但由于某种原因,构造函数没有正确初始化这些值。你能告诉我为什么会发生这种情况吗?

package com.ecuatie;

import com.ecuatie.ecuatie;

public class Start {

  public static void main(String[] args) {
      ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);

      System.out.println(exemplu.delta() + '\n');

      System.out.println(exemplu.X1() + '\n');
      System.out.println(exemplu.X2() + '\n');
  }
}


package com.ecuatie;

import java.lang.Math;

public class ecuatie {
       private double a = 0, b = 0, c = 0;

       ecuatie(double a, double b, double c) {
         this.a = a; this.b = b; this.c = c;
       }

       public double delta() {
         return (b * b) - (4 * a * c);
       }

       public double X1() {
         return (-b + Math.sqrt(delta())) / (2 * a);
       }

       public double X2() {
         return (-b - Math.sqrt(delta())) / (2 * a);
       }
}

【问题讨论】:

  • 你为什么这么认为?
  • 阅读链接的问题以了解您在该程序中的问题(使用双精度而其他问题使用 int 并不重要),然后使用字符串而不是字符。或者根本不使用\n,那是多余的。
  • 您可以使用 + 将字符连接到字符串,但是在您的情况下,您没有字符串,因此它将添加数值。如果你使用了“\n”,你会得到一个错误。如果您需要两个换行符,我会使用 printf(“%f%n%n”, x)。

标签: java


【解决方案1】:

你得到它是因为它添加了字符的 ASCII 值。

'\n' 的 ASCII 值是 10。就像你 + exemplu.delta() 和 10 一样。 使用 println() 时也不需要添加回车。

所以你只需要像这样编写代码。

  public static void main(String[] args) {
  ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);

     System.out.println(exemplu.delta() );

     System.out.println(exemplu.X1() );
     System.out.println(exemplu.X2() );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2012-04-11
    • 2021-04-29
    相关资源
    最近更新 更多