-2

I'm trying to check if a number is a square, and if a number is triangular. The issue is happening at sqrt(num) which is returning 0 for all numbers I test.
I'm using an online compiler, tried several compilers, so it's not a compiling issue. Tried to declare num as a double and as an int, same results.
I'm new to Java, but not new to programming, I searched online, checked my code several times, everything looks fine, it even worked as expected before adding the variables for checking triangular number, but after declaring the variables checkTri and checkTriSqr, this started to happen. I'm sure this have nothing to do with declaring these variables (almost sure), could anyone please help me understand what's going on here?

import static java.lang.Math.sqrt;
import static java.lang.Math.round;

public class Parent{

public static void main(String[] args){

    class Number
    {
        public int num ;
        double numSqr = sqrt(num );
        double roundNumSqr =  round(numSqr) ;
        double checkTri = 8 * num + 1 ;
        double checkTriSqr = sqrt(checkTri) ;

        public void prinTest()
        {
            System.out.println(num);
            System.out.println(numSqr);
            System.out.println(roundNumSqr);
            System.out.println(checkTri);
            System.out.println(checkTriSqr);
        }

        public boolean isSqr()
        {
            if (numSqr == roundNumSqr)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public boolean isTriangular(){

            if (checkTriSqr * checkTriSqr == checkTri )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    Number number = new Number();

    number.num = 350;
    number.prinTest();
    System.out.println(number.isSqr());
    System.out.println(number.isTriangular());
 }
}

EDIT: The following screen shot is from the tutorial I'm following, concerning declaring classes within methods!

enter image description here

Georges D
  • 351
  • 3
  • 11
  • 4
    `num` isn't initialize at all. – user3437460 Dec 18 '17 at 15:34
  • You initialize that number at the time the class is initialized. You should calculate the square root after the user entered some value, I suppose. – Thomas Weller Dec 18 '17 at 15:34
  • 1
    By the way, why is there a class within your `main()` ? – user3437460 Dec 18 '17 at 15:35
  • So should I put it as: int num = 0; ? – Georges D Dec 18 '17 at 15:35
  • If you want to check whether num can be square root, give a value to it like num = 49. But since you wrap your number within a class, create a setter method to update the value for num. – user3437460 Dec 18 '17 at 15:36
  • Well as I said, I'm new to Java, I'm following a tutorial on the subject. @user3437460 – Georges D Dec 18 '17 at 15:37
  • Related: [Default Values and Initialization in Java](https://stackoverflow.com/q/19131336). – Bernhard Barker Dec 18 '17 at 15:55
  • @ThomasWeller well the instructor explained classes, then he said try doing the following yourself, then come back to check the solution, I was doing just that, I didn't get it first time because I said "again.. heavens" I'm new to Java, this why I asked a question in the first place "many people find trial and error a good method to learn" otherwise I wouldn't be here, I hope this answers your question. – Georges D Dec 18 '17 at 16:16

6 Answers6

4

This:

public int num ;
double numSqr = sqrt(num );

initialises num to 0 upon instance construction (the default value for an integer in the absence of assignment), and numSqr is set immediately afterwards (to zero).

You need to recalculate the sqrt() each time you subsequntly set num (perhaps by providing a method setNum() and recalculating everything within that method)

I wouldn't call your class Number, btw. There's already a Number class in the standard Java class set.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

numSqr is created in the constructor, whereas number.num = 350;is declared after the construction of your object.

You can use a constructor like this :

public Numer(int num){
    this.num=num;
    this.numSqr=sqrt(num)
    //.... ... ...
}

You can also use an empty constructor and a setter to set the number attribute :

public void setNumber(int num){
    this.num=num;
    this.numSqr=sqrt(num)
    //.... ... ...
}
Stéphane Ammar
  • 1,454
  • 10
  • 17
2

The values numSqr, roundNumSqr, etc, are all set at the point of the object's creation, however you don't set num to anything until after the object is created. The result is that, for instance,

At creation:

num = 0

therefore

numSqr = 0
roundNumSqr = 0

etc

Then, you set num = 350 But you don't reset the values of numSqr, etc, so this is still the case:

numSqr = 0
roundNumSqr = 0

You need to make a constructor for this class that takes in the value of num and then sets all of the corresponding values, so that they're only set after num has been set (or, add a "calculate" function that updates all the values).

N.D.C.
  • 1,601
  • 10
  • 13
1

You can modify in this way and compare with technology you have worked on .

import static java.lang.Math.sqrt;
import static java.lang.Math.round;


public class Number {

    public int num = 0;

    public void prinTest() {

        System.out.println(this.num);
        System.out.println(this.getSqrt(this.num));
        System.out.println(this.getCheckTri());
    }

    private double getSqrt(double value) {
        return sqrt(value);
    }

    public boolean isSqr() {
        if (this.getSqrt(this.num) == round(this.getSqrt(this.num))) {
            return true;
        } else {
            return false;
        }
    }

    private double getCheckTri() {

        return 8 * this.num + 1;
    }

    public boolean isTriangular() {

        if (this.getSqrt(this.getCheckTri()) * this.getSqrt(this.getCheckTri()) == this.getCheckTri()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {

        Number number = new Number();

        number.num = 49;
        number.prinTest();
        System.out.println(number.isSqr());
        System.out.println(number.isTriangular());

    }
}

You should read some basic tutorials as you have added class inside main method,which means you need more time to check out the syntax.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Rohan Kadu
  • 1,311
  • 2
  • 12
  • 22
0

The other answers alreade said, that the field num was not set to the input number, and that the other fields were actually evaluated on object creation, and hence zero too.

The purpose however is achieved by simple functions:

   public static boolean isSquare(int num) {
       int root = (int) Math.round(Math.sqrt(num));
       return root*root == num;
   }

   public static boolean isCubic(int num) {
       int root = (int) Math.round(Math.cbrt(num));
       return root*root*root == num;
   }

This exploits the cubic root.

As a comparison of doubles, a sqrt result and its rounded long value are still imprecise, I prefer to recalculate the original parameter.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0
public int num ;
double numSqr = sqrt(num);

By default, declared instance integer variables (variables declared inside class body) are initialized with 0 (zero). Hence, your code does nothing but take a square root of zero, which is zero.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52