Program 1: Using Java Scanner Class
/*
Algorithm:
------------
1. Get the length of the square from the user.
2. Calculate its area.
3. Print the area.
*/
//importing java package
import java.util.Scanner;
public class SquareArea1{
public static void main (String[] args){
//creating new Scanner
Scanner sc = new Scanner (System.in);
System.out.println ("Please enter a number ::");
double length = sc.nextDouble();
//calculate area of square
double area = length*length;
//print the area
System.out.println ("Area of the square is :: "+area);
}
}
Save this file as 'SquareArea1.java'
Compile: $javac SquareArea1.java
Execute: $java SquareArea1
Output:
Please enter a number ::
55
Area of the square is :: 3025.0
Program 2: Using Java BufferedReader Class
/*
Algorithm:
------------
1. Get the length of the square from the user.
2. Calculate its area.
3. Print the area.
*/
//importing java packages
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class SquareArea2{
public static void main (String[] args)
throws IOException{
//creating new InputStreamReader
InputStreamReader is = new InputStreamReader(System.in);
//creating new BufferedReader
BufferedReader br = new BufferedReader (is);
System.out.println ("Please enter the length of the square :: ");
double length = Double.parseDouble (br.readLine());
//calculate the area of square
double area = length*length;
//print the area
System.out.println ("Area of the square is :: "+area);
}
}
Save this file as 'SquareArea2.java'
Compile: $javac SquareArea2.java
Execute: $java SquareArea2
Output:
Please enter the length of the square ::
529.15
Area of the square is :: 279999.7225
0 Comments