Wednesday, May 25, 2016

Program to Calculate and Display Area of a Circle


In order to take input I have used the Scanner class, even though you can use other ways like using a Reader or InputStream, but Scanner provides lots of utility method to read any kind of data e.g. int, float, String etc, it's preferred class to read input from the console.


import java.util.Scanner;

public class CircleArea {

public static void main(String[] args) {
// TODO Auto-generated method stub

int r;
double pi =3.14;
double area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius of circle: ");
r = sc.nextInt();
area = pi*r*r;
System.out.println("Area of Circle :"+area);
}
}

If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). Subsequently you can use nextFloat() to read float input, nextDouble() to read double input etc. Scanner class also allows you to define your own pattern and scan for that.
Scanner is created by passing System.in  which is a InputStream as source which means it will scan input console for data.

public class UserInputExample {

    public static void main(String args[]) {
  
        //Creating Scanner instance to scan console for User input
        Scanner console = new Scanner(System.in);
    
        System.out.println("System is ready to accept input, please enter name : ");
        String name = console.nextLine();
        System.out.println("Hi " + name + ", Can you enter an int number now?");
        int number = console.nextInt();
        System.out.println("You have entered : " + number);
        System.out.println("Thank you");
      
    }   
  
}

No comments:

Post a Comment