【问题标题】:How to square a the specified int value?如何对指定的 int 值求平方?
【发布时间】:2017-02-19 09:52:44
【问题描述】:

我收到一条错误消息,提示“无法解析值”

public static MyInt square(MyInt a) {
    double sqred = a.value;
    MyInt sqrObjt = new MyInt(sqred);

    return sqrObjt;
}

这是我的构造函数

public MyInt(int value){
    this.value = value;
}

【问题讨论】:

  • 哪里出错了?
  • MyInt.value 在您的 square 方法中可见吗?
  • 确保 valuepublic
  • square() 定义在什么类中?如果在MyInt 中,应该可以正常工作。如果在另一个班级,那么value 的可见性很重要。

标签: java methods constructor static


【解决方案1】:

我想这里的静态方法不是类MyInt。您可能不想要公共静态方法,这是解决问题的一种更程序化的方法,而不是面向对象的方法。而是向MyInt 类添加一个非静态方法:

public MyInt square() {
    return new MyInt(this.value * this.value);
}

用法:

MyInt squared = someMyInt.square();

【讨论】:

    【解决方案2】:

    确保您已在 MyInt 类中声明了 int 字段值。还要确保在您的 square 方法中将 double 类型转换为整数。对我来说效果很好。

    public class MyInt {
    
        int value; // make sure you don't forget to declare the field
    
        public static MyInt square(MyInt a) {
            double sqred = a.value; // you could've just done int sqred = a.value * a.value rather than have a double
            MyInt sqrObjt = new MyInt((int) sqred); // don't forget to cast sqred to int
            return sqrObjt;
        }
    
        public MyInt(int value){
            this.value = value;
        }
    
    
    
        public static void main(String[] args) {
            MyInt four = new MyInt(4);
            MyInt fourSquares = square(four);
            System.out.println(fourSquares.value);
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      我想你的主要问题是你在课堂上的任何时候都没有声明value。但我扩展了@junvar 给出的答案,包括用于封装的 getter 和 setter。以下是我的做法......

      public class MyInt {
         private int value;
      
         void setValue(int value) { //setter
             this.value = value;
         }
      
         int getValue() { //getter
             return this.value;
         }
      
          int square() { //square method
              int sqred = getValue() * getValue(); 
              return sqred;
          }
      
          public MyInt(int value) { //constructor
              setValue(value);
          }
      
          public static void main(String[] args) { //main to run it
               MyInt testCase = new MyInt(3);
               System.out.println(testCase.square());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-10
        • 1970-01-01
        • 2019-10-31
        • 2014-02-14
        • 2010-10-27
        • 2019-01-05
        • 2015-02-07
        • 2019-12-15
        相关资源
        最近更新 更多