【问题标题】:Scope Issue in java [closed]java中的范围问题[关闭]
【发布时间】:2020-02-09 16:06:35
【问题描述】:
public class Calculator {

    private int total;
    private int value;

    public Calculator(int startingValue){
        int total = startingValue;
        value = 0;
    }

    public int add(int value){
        int total = total + value;
        return total;
    }

    /**
    * Adds the instance variable value to the total
    */
    public int add(){
        int total += value;
        return total;
    }

    public int multiple(int value){
        int total *= value;
        return total;
    }

    public void setValue(int value){
        value = value;
    }

    public int getValue(){
        return value;
    }

}

作业说“对于这个练习,我们将看看另一个 Calculator 类,但是这个已经坏了。计算器类中有几个范围问题阻止它运行。

您的任务是修复 Calculator 类,使其运行并打印出正确的结果。 CalculatorTester 已完成,并且在您修复 Calculator 类后应该可以正常工作。"

我以为我做对了,但它一直告诉我它错了,代码无法运行,我该如何解决这个范围问题?

【问题讨论】:

标签: java scope


【解决方案1】:

在方法total 中再次声明,这样实例变量total 就不会被覆盖。您可以删除方法主体中的int

【讨论】:

  • 这导致了另一个错误。 add(int value) 方法的第一行。说我没有初始化
  • 参考 Bhavya 的回答。
【解决方案2】:
  • 您可以从int total 中删除int,因为它正在创建一个局部变量,并且不需要这样做,因为已经声明了一个私有变量总计private int total;

  • 由于函数参数名和私有变量名相同,即value,所以你应该使用this.value=value而不是value=value;

    private int total;
    private int value;
    
    public Calculator(int startingValue){
        int total = startingValue;
        value = 0;
    }
    
    public int add(int value){
        total = total + value;
        return total;
    }
    
    /**
     * Adds the instance variable value to the total
     */
    public int add(){
        total += value;
        return total;
    }
    
    public int multiple(int value){
        total *= value;
        return total;
    }
    
    public void setValue(int value){
        this.value = value;
    }
    
    public int getValue(){
        return value;
    }
    

【讨论】:

    猜你喜欢
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    相关资源
    最近更新 更多