Reputation: 97
I have some code with no compile errors, but after I enter the second number while its running it crashes on me :(
Heres what I have:
import java.util.Scanner;
public class Assignment536 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
System.out.println("Enter the side: ");
double side = input.nextInt();
System.out.println("The area of the polygon is: " +area(numberOfSides, side));
input.close();
}
public static double area(int n, double side) {
double answer = (n*(side*side))*(4*(Math.tan((Math.PI*n))));
return answer;
}
}
Any help would be greatly appreciated! Thank you, Sebastian
Upvotes: 0
Views: 4127
Reputation: 19
The last part of your formula is wrong. It should be (Math.pi/n) .
import java.util.Scanner;
public class CalcAreaPolygon {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
double area;
final double PI; /method in the formula
double side;
int n;
PI = Math.PI;
System.out.println("Enter the number of sides: ");
n = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the side: ");
side = scanner.nextDouble();
area = (n * (side * side)) / (4 * (Math.tan(PI/n)));
System.out.println("The area of the polygon is " + area);
}
}
Upvotes: 1
Reputation: 850
You should change:
final double side = input.nextInt();
for
final double side = input.nextDouble();
if you want to read a double.
Upvotes: 1
Reputation: 347204
Add input.nextLine()
between the numberOfSlices
and side
request...
System.out.println("Enter the number of sides: ");
int numberOfSides = input.nextInt();
input.nextLine();
System.out.println("Enter the side: ");
double side = input.nextInt();
After requesting numberOfSlices
there is still a carriage return/line feed in the input
buffer, when you try and request the side
value Scanner
fails because it can't convert the the carriage return/line feed to a double
type.
Upvotes: 3