首页 文章

我试图找到定义为数字的对象的总和

提问于
浏览
0

我正在做一个练习,其中我必须创建方法 add ,但是由于p和v被定义为对象,我在练习中给出了'm having a hard time figuring out how I can define this method in the syntax I'(我只允许更改方法) .

我想添加两个输入5和17,以便它返回22.我've done a lot of research into other questions where I'看到他们把它写成 Positiv(p + v) 但这不是很有效 .

public class Positiv {
    public static void main(String[] args) {
        try {
            Positiv p = new Positiv(5);
            Positiv v = new Positiv(17);
            p.add(v);
            System.out.println(p.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private int n;

    public Positiv(int n) {
        if (n < 0) { throw new IllegalArgumentException("exception"); 
        }      
        this.n = n;
        }

    public static Positiv add(Positiv v)
    {
        return new Positiv(n + v);
    }

    public int get() {
        return n;
    }
}

2 回答

  • 0
    public class HelloWorld{
    
         public static void main(String []args){
    
            Numbers a = new Numbers(5);
            Numbers b = new Numbers(10);
    
            int num1 = a.getN();
            int num2 = b.getN();
    
            System.out.println(addTwoNumbers(num1, num2));
    
         }
    
         public static int addTwoNumbers(int a, int b) {
             return a + b;
         }
    }
    
    class Numbers {
        private int n;
    
        public Numbers(int n) {
            this.n = n;
        }
    
        public int getN() {
            return n;
        }
    }
    
  • 4

    在你的 add 方法中:

    public static Positiv add(Positiv v)
    {
        return new Positiv(n + v);
    }
    

    你返回一个全新的 Positiv 对象 . 但是(如果我错了,请纠正我)看起来好像你只想添加两个 n 字段 . 您可以通过将 this.get 添加到 v.get 来执行此操作:

    public void add(Positiv v)
    {
        this.n += v.get();
    }
    

    哪个会返回 22


    this教程

相关问题