如何使用类从Mutator / setter获取值

时间:2017-11-13 18:37:52

标签: java

美好的一天!我试图使用(此。操作符)获取num1和num2的值,但无论我做什么,我只是不能把这两个数字的值放在num3上。我目前是java编程的新手,这就是我在语法上不熟悉的原因。

我的代码:

public class FinalProject 
{

    public  Double num1;
    public  Double num2;
    public  Double num3;

public FinalProject ()
{

    this.num1 = 0.0;

    this.num2 = 0.0;

    this.num3 = 0.0;

}

public void setNum1(Double num1) //setter1
 { 

    this.num1= num1;

  }

public void setNum2(Double num2) //setter2
 {

    this.num2= num2;

  }

public void setNum3(Double num3) //setter3
{

   value3 = this.value1 + this.value2;

    this.num3 = num3;

  }

--------------- // GETTER -----------------

public Double getNum1()
 {

    return this.num1; 

  }

public Double getNum2()
 {

    return this.num2;

  }

public Double getNum3()
 {

    return this.num3; 

  }

}

------------------- //我的主要课程-----------------

package finalproject;

import java.util.Scanner;

public class FinalProjectMain {

    public static void main(String[] args) 
    {


        Scanner input = new Scanner(System.in);

        FinalProject output1 = new FinalProject();//num1
        FinalProject output2 = new FinalProject();//num2
        FinalProject output3 = new FinalProject(); //num3

        System.out.print("Enter your 1st number: ");
        output1.setNum1(input.nextDouble());

        System.out.print("Enter your 2nd number: ");
        output2.setNum2(input.nextDouble());


        System.out.print("The sum of two number is: " + output3.getNum3());




    }
}

1 个答案:

答案 0 :(得分:2)

你真的需要考虑你希望public void setNum3(Double num3) //setter3 { value3 = this.value1 + this.value2; this.num3 = num3; } 的行为方式。目前的状态:

num3

它无法编译。您似乎尝试将参数分配给num1,同时还要加num2setNum3

在我看来,您不需要num3num1字段。只需在num2方法中添加getNum3public Double getNum3() { return this.num1 + this.num2; } 的逻辑:

FinalProject

另外,您应该只在主体中创建一个Scanner input = new Scanner(System.in); FinalProject output = new FinalProject(); System.out.print("Enter your 1st number: "); output.setNum1(input.nextDouble()); System.out.print("Enter your 2nd number: "); output.setNum2(input.nextDouble()); System.out.print("The sum of two number is: " + output.getNum3()); 实例,如下所示:

SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'  
             WHEN [COL] = 'AD' THEN 'Aging'
             WHEN [COL] = 'Art' THEN 'Artwork'  
             ELSE 'Some Default value'    -- or don't add ELSE if not required
        END
    FROM #test_a