andris
andris

Reputation: 99

Java OOP triangle existence

I have recently started with programming. So far I have learned basics and now its time for OOP and so i have some questions as im building basic programs to just understand principals and link to way I would use it in practical ways.

So I am making simple triangle program in Java, so far it calculates perimeter (later will ad other shapes and other parameters), I hit the wall where I want to add Triangle existence (as side can't be negative) and also Id like to allow user input. Thing is i don't know where to put code and how to refer to class. Linear (non OOP) way it is simple, but how its done in OOP, do i have to make another class or in Triangle class via methods?

my code:

public class Trissturis {
    private int sideA, sideB, sideC;
    private double perimeter;

    public Trissturis(int a, int b, int c) {
        sideA = a;
        sideB = b;
        sideC = c;
    }

    public double getPerimeter() {
        return sideA + sideB + sideC;
    }
}

public class TestTri {
    public static void main(String[] args) {

        Trissturis t1 = new Trissturis(10, 20, 30);
        System.out.println("perimeter is  " + t1.getPerimeter());

        Trissturis t2 = new Trissturis(-1, 20, 30);

    }
}

Upvotes: 0

Views: 2366

Answers (3)

Eduardo
Eduardo

Reputation: 8402

To validate the triangle you have to check that all sides have a length greater than zero, and that no side is longer than the sum of the other two. An method that would accomplish this is:

public boolean isValid(){
    return (sideA>0)&&(sideB>0)&&(sideC>0)&&(sideA+sideB>sideC)&&(sideA+sideC>sideB)&&(sideC+sideB>sideA);
}

For the user to input values, it is better to have separate user-interface classes. If this will be a desktop application, you could use some of the Swing classes, for example (although there are alternatives).

Upvotes: 3

jdevelop
jdevelop

Reputation: 12296

interface TriangleFactory {

  Triangle create();

}

class ConsoleTriangleFactory implements TriangleFactory {
  @Override
  Triangle create() {
    // read perimeter from console here with some nice prompt
    // check that every side is > 0, 
    // if it's not a number or less than 0 - then do some alert
  }
}

Upvotes: 2

mcalex
mcalex

Reputation: 6798

Your code to check that the triangle is constructed correctly (with non-negative values, etc) belongs in the Triangle class.

Code to take user input can go in main() in your Test for a small program, but could go in a separate UI namespace for a larger application.

hth

Upvotes: 1

Related Questions