Skip to content

Instantly share code, notes, and snippets.

@lablnet
Last active November 3, 2020 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lablnet/1e555e9e3152866eac0044d3bb655bfb to your computer and use it in GitHub Desktop.
Save lablnet/1e555e9e3152866eac0044d3bb655bfb to your computer and use it in GitHub Desktop.
OOP Class Assignment 01
package com.company;
import java.util.Scanner;
class Rectangle {
private double length;
private double width;
private boolean error;
public Rectangle() {
this.length = 1;
this.width = 1;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public boolean isError()
{
return this.error;
}
public Rectangle setLength(double length) {
this.error = false;
if(length >= 0 && length < 20 && length == (double) length) {
this.length = length;
} else {
this.error = true;
System.out.println("Please enter between 0 to 20, and should be float");
}
return this;
}
public Rectangle setWidth(double width) {
this.error = false;
if(width >= 0 && width < 20 && width == (double) width) {
this.width = width;
} else {
this.error = true;
System.out.println("Please enter between 0 to 20, and should be float");
}
return this;
}
public void calculatePerimeter(){
System.out.println("Perimeter of rectangle is: " + 2 * (this.length + this.width));
}
public void calculateArea(){
System.out.println("Area of rectangle is: " + (this.length * this.width));
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Rectangle r = new Rectangle();
while (true) {
System.out.println("Enter length");
double l = scanner.nextDouble();
System.out.println("Enter width");
double w = scanner.nextDouble();
r.setWidth(w).setLength(l);
if (!r.isError()) break;
else {
System.out.println("Try again.");
}
}
r.calculateArea();
r.calculatePerimeter();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment