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