Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java Infinite Loop in Java Error?

aartiyadav

New Coder
Hello Everyone, I am new in this community and new to Java and am attempting to write code that takes the number of sides of a polygon and the length of each side as input and gives the area of the polygon as output. The JRE I am using says that my code will not run, possibly because of an endless loop. I do not see any errors in my code, but I have an untrained eye so any help would be greatly appreciated. I'm using the online compiler on https://www.interviewbit.com/online-java-compiler/ Below is my code.

Java:
import java.util.Scanner;

public class Exercise04_05{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of sides: ");
        double num = input.nextInt();

        System.out.println("Enter the side: ");
        double side = input.nextInt();

        double area = (num*side*side) / (4 * Math.tan(Math.PI / num));

        System.out.print("the area of the polygon is: " + area);
    }
}
 
That looks totally straightforward, and there's certainly no endless loop here.

Actually when I paste this into your online compiler and click Run, it doesn't even compile, because the class Exercise04_05 should be declared in Exercise04_05.java. I see no way to define a file name here.

But the 'normal' Java compiler has absolutely no problem with this program, see:

Code:
D:\Temp>java -version
java version "17.0.1" 2021-10-19 LTS
Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.1+12-LTS-39, mixed mode, sharing)

D:\Temp>javac Exercise04_05.java

D:\Temp>java -cp . Exercise04_05
Enter the number of sides: 4
Enter the side:
3
the area of the polygon is: 9.000000000000002
D:\Temp>
 
Back
Top Bottom