user5916063
user5916063

Reputation:

How to square a the specified int value?

Im getting an error saying "value cannot be resolved"

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

    return sqrObjt;
}

Here is my constructor

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

Upvotes: 0

Views: 394

Answers (3)

msleevi
msleevi

Reputation: 124

I would imagine your main problem is the fact that you never declare value at any point during the class. But I expanded on the answer @junvar gave to include getters and setters for encapsulation. Here is how I would do it....

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());
    }
}

Upvotes: 0

weston
weston

Reputation: 54801

I suppose the static method here is somewhere other than the class MyInt. You probably do not want a public static method, that's a more procedural approach to the problem rather than an Object-Orientated one. Instead add a non-static method to the class MyInt:

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

Usage:

MyInt squared = someMyInt.square();

Upvotes: 2

junvar
junvar

Reputation: 11594

Make sure you have declared the int field value in your MyInt class. Also make sure to cast the double to an integer in your square method. It works fine for me.

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);
    }

}

Upvotes: 1

Related Questions