int reverse sign negate()java

时间:2012-10-26 06:45:19

标签: java methods logic negate

要求

假设现有类ICalculator的可用性,它为整数算术计算器建模并包含:

  • 存储当前int值的实例变量currentValue 计算器,可以被任何子类访问和修改。

  • 方法add,sub,mul和div

    ICalculator中的每个方法都接收一个int参数,并将其操作应用于currentValue并返回currentValue的新值。因此,如果currentValue的值为8且调用了sub(6),则currentValue以值2结束,并返回2。

因此,您要编写基于ICalculator的子类ICalculator2的定义。 ICalculator2类有一个额外的方法,否定,不接受任何参数。否定的效果是反转currentValue的符号。例如,如果currentValue为零,则没有变化,如果是-22则变为22,如果为100,则变为-100。此外,否定返回currentValue的新值。

源代码

public class ICalculator2 extends ICalculator {
public int negate() { 
int val = add(0);      
if (val == -22) return val * -1;   
else if (val == 100) return val * -1;   
else return 0;}}

说明:

  • 您的代码在执行期间出错

更多提示:

  • 您可能希望使用100以外的数字

  • 您可能希望使用22

  • 以外的数字
  • 您确定要使用:val

提示:

  • 您可能想要使用:<
  • 您确定要使用:=

6 个答案:

答案 0 :(得分:12)

你不需要做任何奇怪的计算。试试这个:

public class ICalculator2 extends ICalculator {
    public int negate() { 
        return (currentValue = -currentValue);
    }
}

答案 1 :(得分:2)

您可以通过操作ICalculate类中为您提供的方法来完成此操作。请记住,您不能直接使用实例变量currentValue,因为它是私有变量,并且子类只能通过方法访问私有变量。在这种情况下,最好的操作方法是mul(),参数为-1。

public int negate(){

return mul(-1); }

答案 2 :(得分:0)

请尝试这样可以帮助您解决此问题

        int i = -22;
        i = i*-1;

        System.out.println(i);
            return i;

答案 3 :(得分:0)

您获得的数字就是一个例子。如果有使用任何其他数字的真值表,您的示例将失败。这就是代码存在问题的原因。 您需要使用代码来显示当currentValue不为0时会发生什么。

查看以下内容:

    public class ICalculator2 extends ICalculator {
        public int negate() {
          if (currentValue != 0) {
            return currentValue * -1;}
          else {
            return 0; 
            }
        }
    }

答案 4 :(得分:0)

我刚刚注意到您正在尝试扩展常规作为接口的内容。那不行。您实施接口。

答案 5 :(得分:-1)

老兄,你错了。

公共类ICalculator2扩展了ICalculator {

public int negate(){
    int val =mul(-1);
    return val;}}
你知道吗? -22和100是例子,它们并不重要。关键在于你需要否定它是什么。

相关问题