简体   繁体   English

Java不打印?

[英]Java not printing?

When i try calling out my method it prints 0 why is this?当我尝试调用我的方法时,它会打印 0,这是为什么? am.area() " but if i take out the baseprice variable in the formula it prints out correctly how do i correct this? also i wanted to try out Associaton but i don't know how to use it. am.area() "但如果我在公式中取出 baseprice 变量,它会正确打印出我该如何更正?我也想尝试 Associaton,但我不知道如何使用它。

class Base {
     double baseprice;
     public void setBaseprice(int bp) {
     baseprice = bp;
     }
     public double getBaseprice() {
     return baseprice;
     }
}

class ID{
     int agentId;
        ID(int Id)  {
        this.agentId=Id;
       }
 }
class Agent{
            String agentName;
            Agent(String name){
            this.agentName=name;
  }
}
class AreaMinor extends Base {
double sides;
              public AreaMinor(int s) {
              sides = s;
          }  
public void area() {
    double sum = sides*sides*(4+Math.sqrt(3))/4;
    double area = sum*baseprice;
    System.out.print(area);
 }  
}

public class Main  {
 public static void main(String args[]) {
java.util.Scanner kbd = new java.util.Scanner(System.in);

 System.out.print("Enter your lot type ");
 lot = kbd.nextInt();

 if(lot == 1) {
  System.out.print("Enter the Sides ");
  int side = kbd.nextInt();
  AreaMinor am = new AreaMinor(side);
  am.area();                //why does it this line print 0

baseprice is set to 0 by default, then result 0xK = 0 . baseprice 默认设置为 0,则结​​果为 0xK = 0 。 Normal普通的

you should add am.setBaseprice(3);你应该添加am.setBaseprice(3); in main method (if you want the baseprice to be 3) otherwise it is initialized to 0在 main 方法中(如果您希望 baseprice 为 3),否则将其初始化为 0

alternatively, you can call the setter in the constructor of AreaMinor或者,您可以在AreaMinor的构造函数中调用 setter

also note that if baseprice setter accepts int values, I see no reason for it to be typed double另请注意,如果 baseprice setter 接受 int 值,我认为没有理由将其键入 double

In your Base Class, you've declared the baseprice variable as double and not explicitly declared a value by calling that constructor.在您的Base类中,您已将baseprice变量声明为 double 并且未通过调用该构造函数显式声明值。
Therefore, the problem is that you haven't initialised the baseprice variable, Hence, it is by default 0.0因此,问题是您尚未初始化baseprice变量,因此,默认情况下为 0.0

...
AreaMinor am =  new AreaMinor(side);
am.setBasePrice(3);
am.area();
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM