dimanche 24 janvier 2016

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.

In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.

I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.

public class HelloWorld {
  public static void main(String[] args) {
    class NumberShape {
        int num = 45;
        int tri = 0;
        int triplus = 0;
        String triresult;

        public String triangle() {

            while (tri < num) {
                if (tri == num) {
                    triresult =  "Is a Triangle";
                    System.out.println("Is a Triangle");
                } else if (tri + (triplus + 1) > num){
                    triresult =  "Is Not a Triangle";
                } else {
                    triplus++;
                    tri = tri + triplus;
                }
            }
            return triresult;
        }
    }

    NumberShape result = new NumberShape();
    System.out.println(result.triangle());
    }
}

Thanks for any help provided.

Aucun commentaire:

Enregistrer un commentaire