fork download
  1. import java.util.Scanner;
  2.  
  3. abstract class Forma {
  4. public void imprime() {
  5. System.out.println("Área: " + area());
  6. System.out.println("Perímetro: " + perimetro());
  7. }
  8. public abstract double area();
  9. public abstract double perimetro();
  10.  
  11. }
  12.  
  13. class Retangulo extends Forma {
  14. private double comprimento;
  15. private double largura;
  16.  
  17. Retangulo(double comprimento, double largura) throws Exception {
  18. if (comprimento <= 0 || largura <= 0) throw new Exception("ONDE JÁ SE VIU LARGURA E/OU COMPRIMENTO NEGATIVO?");
  19. this.comprimento = comprimento;
  20. this.largura = largura;
  21. }
  22.  
  23. @Override
  24. public double area() {
  25. return comprimento * largura;
  26. }
  27. @Override
  28. public double perimetro() {
  29. return 2 * (largura + comprimento);
  30. }
  31. public double getComprimento() {
  32. return comprimento;
  33. }
  34. public double getLargura() {
  35. return largura;
  36. }
  37. public void setComprimento(double comprimento) throws Exception {
  38. if (comprimento < 0) throw new Exception("ONDE JÁ SE VIU COMPRIMENTO NEGATIVO?");
  39. this.comprimento = comprimento;
  40. }
  41. public void setLargura(double largura) throws Exception {
  42. if (largura < 0) {
  43. throw new Exception("ONDE JÁ SE VIU LARGURA NEGATIVA?");
  44. }
  45. this.comprimento = largura;
  46. }
  47. }
  48.  
  49. class Programa {
  50. public static void main(String[] args) {
  51. Scanner sc = new Scanner(System.in);
  52. double comprimento = sc.nextDouble();
  53. double largura = sc.nextDouble();
  54. try {
  55. Retangulo retangulo = new Retangulo(comprimento, largura);
  56. retangulo.imprime();
  57. retangulo.setComprimento(-comprimento);
  58. } catch (Exception ex) {
  59. System.out.println(ex.getMessage());
  60. }
  61. }
  62. }
  63.  
  64. //https://pt.stackoverflow.com/q/148081/101
Success #stdin #stdout 0.15s 38164KB
stdin
12
8
stdout
Área: 96.0
Perímetro: 40.0
ONDE JÁ SE VIU COMPRIMENTO NEGATIVO?