0

I write a code in netbeans with the purpose of calculating the area of a pentagon, I wrote it with all the variables of type double. The problem is that when I enter a double to test the code the application prompt a mismatch exception.

I enter an int variable and it works, I have tried to change the code but it doesn't work.

package ejercicios.de.practica.capitulo4_5;


import java.util.Scanner;

public class EjerciciosDePracticaCapitulo4_5 {
    public static void main(String[] args) {
        // Crear variables
        double Area, s, r;
        final double PI= 3.1416;
        final double TREINTAYSEIS= PI/5;
        Scanner input= new Scanner (System.in);
        System.out.println(" Enter the lenght from a center to a vertex of the pentagon:  ");
        r= input.nextDouble();
        s= 2*r*(Math.sin(TREINTAYSEIS));
        Area= (5*(Math.pow(s,2)))/4*(Math.tan(TREINTAYSEIS));
        System.out.println("The area of the pentagon is  " + Area);     
    }

}

If I enter the length from the center to a vertex: 5.5 the area of the pentagon is expected to be 71.92, but in my program, it doesn't accept the double input. I have to enter the int 5 and the result was 37.7007586539534.

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mily
  • 1
  • 2

1 Answers1

1

It's because your Area equation is not calculating in the sequence you expect. You will need to be a little more specific towards how you want the equation to calculate. Portions of the equation that are contained within brackets are always calculated first so with that in mind:

Instead of:

Area= (5 * (Math.pow(s, 2))) / 4 * (Math.tan(TREINTAYSEIS));

Do this:

Area = (5 * Math.pow(s, 2)) / (4 * Math.tan(TREINTAYSEIS));

Place parentheses around 4 * Math.tan(TREINTAYSEIS). You have a lot of unnecessary bracketing and should get rid of it as I have done since all it does is clutter things up. Also spacing things out can help you see things a little clearer. Personally, if I do double calculations then I try to use all doubles in that calculation:

Area = (5.0d * Math.pow(s, 2.0d)) / (4.0d * Math.tan(TREINTAYSEIS));

On a side note: If you are only going to use PI to a precision of 4 then perhaps you should consider doing all your calculations to that precision.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22