有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java第二次打印出节省的资源

因此,我已经编写了大部分代码,但我需要帮助的一部分,这是所有的方式在代码的底部。所以我制作了一个保存2531.5的对象,这样我可以打印出来作为Gob先生的初始保存,但是你必须在Gob先生的保存中添加25000,然后再次打印出来,它打印出与第一个相同的东西,即2531.5。输出结果应该是这样的https://gyazo.com/631227169fa677fa389fd029db146ed4。我只是对我该如何做任务6感到困惑,不知道我做错了什么

public class Gob
{
    //The following are IF/IV
    public String position;
    public int age;
    //task #1 create an Instance Field "saving" as type double
    public double saving;
     //your work here    
    public Gob(double d){
        //task #2 initialize the saving to user input
        
        
        saving = d;
        //your work here
        
        
        position = "Teacher";
        age = 55;
    }

    //task #2 create a method printPosition() to print out position
    //in the following format
    //    "My position is a _______"

    public void printPosition(){
        
        System.out.println("My position is a " + position);
    }
    
    //task #3 create a method to print out saving 
    //you need to create a whole new method

    public void printSaving(){
        System.out.println("My saving is "+ saving);
    }
    
    //task #4 complete the method below 
    //add the input amount to the saving you have 

    public void addSaving(double e){
       e = saving;
     } 
    
    public static void main(String args[]){
        //Create an new object with saving = 2531.50
        Gob h = new Gob(2531.50);
        h.printPosition(); //this is the name of the method
        //Task #5 print out the initial saving of Mr. Gob
        //your work here
       h.printSaving();
        
        
        //Task #6 add 25,000 to Mr. Gob saving and then
        //print the saving again
        //your work here
        h.printSaving();
        
    }
}

共 (3) 个答案

  1. # 1 楼答案

    public void addSaving(double e){
       e = saving;
    }
    

    执行此操作时,将要修改的字段的当前值指定给要传递的参数。它应该是另一种方式,您应该添加值,而不是用另一个值替换一个值。那么像这样,

    public void addSaving(double e){
       this.saving = this.saving + e;
    }
    

    同样在main()方法中,我没有看到您调用addSaving()。如果你还没有这样做,你也需要这样做

  2. # 2 楼答案

    您的公共void addSaving(双e)代码不会将e添加到此的运行总数中。节省物您需要将public void addSaving(双e)更改为

    公共无效添加保存(双e){

      this.saving += e;
    

    }

    然后调用h.addSaving(25000.00);之后,您可以使用打印方法再次打印储蓄金额

  3. # 3 楼答案

    两件事:

    1:纠正下面的方法。 您没有将变量添加到类的引用变量(保存)

     public void addSaving(double e){
     //  e = saving;  **should be as below** 
     this.saving += e;
      
     } 
    

    2:在第二次调用printSaving之前,您需要调用addSaving(一些双精度值),这实际上将与旧的保存相加。 大概 h、 增加储蓄(500.0); h、 打印保存()