【问题标题】:How to call a method from another method in the same class (java)如何从同一个类中的另一个方法调用一个方法(java)
【发布时间】:2016-03-09 20:13:10
【问题描述】:

我一直在尝试通过阅读“Java 如何对早期对象进行编程”来了解如何从同一类的另一个方法中调用方法。

此刻我完全迷失了,书中使用的类比让我很容易想象正在发生的事情。但是,将其转换为代码具有挑战性。

我已经尝试了很多次来解决这个问题并且已经走到了这一步: P.S. 为了简单起见,我排除了我认为对我的问题不重要的代码...

import java.util.Scanner;

public class BuyAHouseInc
{
    private int housePrice;
    private int amountOfHouses;
    private int houseCounter;

    // method to enter the amount of houses on sale
    public void setAmountOfHouses()
    {
        // do stuff etc.
    }

    // method that sets the house price
    public void setHousePrice()
    {
        // do stuff etc.

        calculateFees(this.housePrice); // this is where I'm not sure...
    }

    //method to calculate fees and taxes
    public void calculateFees(int housePrice) // does this receive this.housePrice?
    {
      // do some stuff
    }

测试代码:

public class BuyAHouseIncTester
{
    public static void main(String[] args)
    {
        BuyAHouseInc client1 = new BuyAHouseInc("John","Doyle","15 Newton Drive\nDublin 5\n", 550000) // Create object 
        // set amount of houses on sale to client 1
        client1.setAmountOfHouses(); 

        // set house price for each of the houses added to database
        client1.setHousePrice();
    }
}

在另一个方法中调用一个方法的代码是什么?是否调用了每个单独房价的值?

【问题讨论】:

  • 再一次,为什么不放一些 System.out.println() 语句并测试它,或者使用调试器运行它?您问“是否会调用每个单独房价的值?”。但他的问题没有意义:这段代码中有一个 single housePrice。
  • AFAIK,除非你使用static imports,否则非限定方法调用(比如说x())只能解释为this.x()super.x()this.x() 优先。 (例外:在内部类的情况下,它也可以解释为EnclosingClass.this.x()。那么不确定优先级。)
  • 没有代码提示什么。根本没有循环。您在问自己 calculateFees 是否收到 this.housePrice。所以在调用 calculateFees() 方法之前打印 this.housePrice(),并在 calculateFees() 打印 housePrice 参数。
  • @JB Nizet 我在代码背后的想法是,您输入第一个房价并在calculateFees 方法中执行所有代码,然后提示用户输入第二个房价,依此类推。您会将打印语句放在哪里来调试代码?
  • @JBNizet 正如我所料,它会打印我输入的最后一个房价。我将如何将每个房价传递给我程序中的所有方法并“对第一所房子做一些事情”,然后我进入第二所房子等等。

标签: java oop methods


【解决方案1】:

您可以简单地调用calculateFees(housePrice);,因为在调用点唯一可见的housePrice 变量是instance variable private int housePrice;

假设您有一个 constructor 调用来根据您创建 BuyAHouseInc 的方式设置 housePrice

//费用和税金的计算方法 public void calculateFees(int housePrice) // 这会收到 this.housePrice 吗? { // 做一些事情 }

是的,这将收到通过calculateFees(housePrice); 传递的housePrice

calculateFees(int housePrice) 上面定义的局部变量只在calculateFees(int housePrice){...}方法内部可见

Passing Information to a Method or a Constructor

更新:基于 cmets,您需要更新您的 setter 以传递房价

public void setHousePrice(int housePrice)
    {
        this.housePrice = housePrice;

        calculateFees(this.housePrice); 
    }

【讨论】:

  • 谢谢你,我会试试我所有的方法
  • 我试过了,但在测试器类中出现错误...方法不能应用于给定类型,类型是双重的,没有参数...你能解释一下这里出了什么问题?
  • 你有对BuyAHouseInc的构造函数调用吗?\
  • 如果您遇到错误,请发布堆栈跟踪。猜测是您传递的是双精度数(带小数点的数字)而不是整数。
  • 在我的完整版代码中,我有一个构造函数,但我只传递了客户的详细信息,例如姓名、地址和预算。我没有在构造函数中传递任何房价或类似的东西。
【解决方案2】:

是的,你的假设是正确的。

但是,有一些重要的事情需要注意。这段代码:

public void setHousePrice()
{
    // do stuff etc.

    calculateFees(this.housePrice); // <---This probably doesn't do what you think it does
}

// No. This doesn't receive this.housePrice. It receives the VALUE of this.housePrice. 
// It's a completely new variable
public void calculateFees(int housePrice) .
{
  // do some stuff
}

Java 是按值传递的。您正在传递 housePrice 的值,但并未修改原始 housePrice。

因此,如果您“做一些事情”并修改传入的 housePrice 变量,除非您在 calculateFees 中设置 housePrice,否则这些更改不会保存。

在这种情况下,最好通过 getter/setter 来操作任何成员变量。顺便说一句,约定是 setter 应该总是取值。这不是任意的,因为许多库都依赖于 set/get 方法以某种方式发挥作用。

我已将上述答案编辑得更清楚。

【讨论】:

  • 哦!它是一个全新的变量……有帮助!所以要存储 this.housePrice,calculateFees(int housePrice) 参数不能有相同的名称,所以将其从 housePrice 更改为 houseCost?
  • 名称可以相同。这里有点奇怪。假设您在 calculateFees(housePrice) 内部,housePrice 将引用传入的值。this.housePrice 将引用属于该对象的成员变量。
  • 我对 Java 又爱又恨......我在修补我目前几乎不理解的东西。这是我发现的最好的学习方式。
【解决方案3】:

如果我错了,请纠正我,但这是一个可能的解决方案:

public void setHousePrice(int price)
{


    calculateFees(price); 
}


public void calculateFees(int housePrice) 
{
  // stuff with housePrice
}

然后做

variable.setHousePrice(variable.getHousePrice);

【讨论】:

    【解决方案4】:
    public class BuyAHouseInc {
        private double housePrice;
        private int amountOfHouses;
        private int houseCounter;
    
        public BuyAHouseInc(double housePrice, int amountOfHouses, int houseCounter) {
            this.housePrice = housePrice;
            this.amountOfHouses = amountOfHouses;
            this.houseCounter = houseCounter;
        }
    
        // method that sets the house price
        public void generateHousePrice() {
            // do stuff etc.
            // you could also put the logic in the set method... Had to change the method name to 
            // generate as the getters and setter where created and the setter method is named
            // exactly like your previous method
            calculateFees(housePrice); // this is were I'm not sure...
        }
    
        // method to calculate fees and taxes
        public void calculateFees(double housePrice) // does this receive
                                                        // this.housePrice?
        {
            // do some stuff
        }
    
        public double getHousePrice() {
            return housePrice;
        }
    
        public void setHousePrice(double housePrice) {
            this.housePrice = housePrice;
        }
    
        public int getAmountOfHouses() {
            return amountOfHouses;
        }
    
        public void setAmountOfHouses(int amountOfHouses) {
            this.amountOfHouses = amountOfHouses;
        }
    
        public int getHouseCounter() {
            return houseCounter;
        }
    
        public void setHouseCounter(int houseCounter) {
            this.houseCounter = houseCounter;
        }
    
        @Override
        public String toString() {
        return "BuyAHouseInc [housePrice=" + housePrice + ", amountOfHouses=" + amountOfHouses + ", houseCounter="
                + houseCounter + "]";
    }
    
    
    }
    

    将两个类分开在不同的文件中。需要指出的另一件事是使用 double 作为价格而不是 int。 您还必须创建 getter 和 setter 才能获取和设置您的属性。 您还必须在类中添加一个构造函数。然后您可以在 main 中创建该类的实例并调用其方法。 主要方法如下所示。

    public class Main {
    
        public static void main(String... args) {
            BuyAHouseInc test = new BuyAHouseInc(200000, 4, 2);
            test.setAmountOfHouses(6); // changed from 4 to 6
            test.generateHousePrice();
            test.calculateFees(test.getHousePrice());
            test.toString();
    
        }
    }
    

    希望你觉得这很有帮助,祝你好运!我已经编辑了代码并添加了 toString 方法以将信息输出为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 2011-01-15
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2017-10-17
      相关资源
      最近更新 更多