In: Computer Science
public class Square {
public static final int NUM_OF_SIDES = 4;
private float length;
public Square(float l) {
setLength(l);
}
public void setLength(float l) {
if(l >= 0) {
length =
l;
}
}
public float getLength() {
return length;
}
//TODO - Add method to calculate add return area
//TODO - Add method to calculate add return
perimeter
public String toString() {
return String.format("Square
[length: %f]", length);
}
}
I am trying to add the formulas for area and perimeter but using the info provided each time I get a compile error indicating I am missing a main method. How would I go about adding these formulas without getting more compile errors?
Code - You have to add the main method in any of the java program , because main method is entry point for any of the java program , if java compiler doesnt find the main method then it will give error , I have added main method and also area and perimeter method below -
Square.java -
public class Square {
public static final int NUM_OF_SIDES = 4;
private float length;
public Square(float l) {
setLength(l);
}
public void setLength(float l) {
if(l >= 0) {
length = l;
}
}
public float getLength() {
return length;
}
//TODO - Add method to calculate add return area
float calcArea(){
float len = getLength();
return len*len;
}
//TODO - Add method to calculate add return perimeter
float calcPerimeter(){
return NUM_OF_SIDES *length;
}
public String toString() {
return String.format("Square [length: %f]", length);
}
//main method added
public static void main(String []args){
//created object of square
Square s = new Square(5);
System.out.println("Length "+s.toString());
System.out.println("Area "+s.calcArea());
System.out.println("Paramter "+s.calcPerimeter());
}
}