Java

Compute and Display Area of a Circle in Java

Programmingempire

The following code example shows how to Compute and Display Area of a Circle in Java. Apart from being a simple program, it lets you learn many useful basic concepts of Java programming language when you have just started learning. The following section describes some of the important points.

Accepting Input from User

In order to read a string from a character-based input stream, we can use the BufferedReader class. Therefore we create an instance of this class for creating a buffered character input stream. For example,

BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));

After that, we can call the readLine() method from the instance to read next line of input. For example,

String str=bfr.readLine();

Since, we need a double type value, so we convert this string to double type value.

Converting string to Double

For the purpose of converting a string to a value of another type, we can use wrapper classes. So, we can use the parseDouble() method of the Double class that converts a string to double value. Also, this method throws a NullPointerException when the string passes is null. Moreover, it throws a NumberFormatException when the string passedis not convertible to double. The following example demonstrates it.

import java.io.*;
public class Main
{
	public static void main(String[] args) throws IOException {
	    double x;
		System.out.println("Enter a double type value: ");
		BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
		x=Double.parseDouble(bfr.readLine());
		System.out.println("x = "+x);
	}
}

Output

NumberFormat Exception Thrown
NumberFormat Exception Thrown

Since, the input value entered is ‘abc’, which can’t be converted to double, so this exception is thrown.

Declaring the IOExcption by main() Method

In order to handle the problems that may arise during the execution of a method, the method can declare a particular exception. Therefore, now the main() method doesn’t handle the IOException. Rather, it throws this exception to the source, that has invoked the main method, that is the Java Virtual Machine (JVM). Hence, JVM handles the IOException.

Program to Compute and Display Area of a Circle in Java

import java.io.*;
public class Main
{
	public static void main(String[] args) throws IOException {
	    double rd, circle_area;
		System.out.println("Enter the radius of the circle: ");
		BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
		rd=Double.parseDouble(bfr.readLine());
		circle_area=3.14*rd*rd;
		System.out.println("Area of Circle: "+circle_area);
	}
}

Output

The Output of Program to Compute and Display Area of a Circle in Java
The Output of Program to Compute and Display Area of a Circle in Java
programmingempire

You may also like...