Area of Circle :
In this post we are discussing about Area of Circle in Java but Rules 2 for beginner and Advance.
Program :
import java.util.*; // It it mandatory for both rules >>follow up rules 2 explanation
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Rule 1: Using BufferedReader
class CircleArea{
public static void main(String arg[]){
int raduis = 0;
System.out.println("Please Enter Raduis of a Circle: ");
try{
// get the raduis from console
BufferedReader br= new
BufferedReader(new InputStreamReader(System.in));
raduis = Integer.parseInt(br.readLine());
}
// if invailed value was entered
catch(NumberFormatException ne){
System.out.println("Invailed raduis value"+ne);
System.exit(0);
}
catch(IOException ioe){
System.out.println("IO Error: "+ ioe);
System.exit(0);
}
double area = Math.PI * raduis* raduis;
System.out.println("Area of Circle is:"+ area);
}
}
Explanation:
- BufferReader and InputStramReader:
- BufferedReader reads input more efficiently.
- InputStramReader(System.in) converts the byte stream(Keyboard input ) to character stream.
- Error Handling:
- NumberFormatException: Catches invalid numeric input( e.g user enters "abc" instead of a number)
- IOExecption: Handles I/O errors during input reading.
- NumberFormatException: Catches invalid numeric input( e.g user enters "abc" instead of a number)
- IOExecption: Handles I/O errors during input reading.
- Calculation: Uses Math.PI for accurate value of π
Rule 2: Using Scanner
class CircleArea1{
public static void main(String arg[]){
int raduis;
System.out.println("Please Enter Raduis of a Circle: ");
Scanner in = new Scanner(System.in);
raduis = in.nextInt();
double area = 3.14 * raduis*raduis;
System.out.println("Area of Circle is :"+ area);
}
}
Explanation:
- Scanner
- Simple than BufferedReader.
nextInt()
directly reads an integer, reducing the need forparseInt
.- Calculation:
- Uses 3.14 as an approximations for PIE
- No Explicit Error Handling:
- If invalid input (e.g., non-integer) is provided, the program will throw an exception without catching it. You can improve it by wrapping
nextInt()
in atry-catch
block for robustness.
Key Differences:
- Better for reading large input or multiple lines.
- Requires explicit conversion for numeric data.
- Needs
IOException
handling.
- Easier to use for simple, interactive input.
- Direct methods like
nextInt()
simplify data retrieval. - No need for explicit
IOException
handling but prone to runtime errors for invalid input.
Comments