Thursday, 1 August 2013

Get Input from user using Scanner

This program tells you how to get input from user in a java program through command prompt or using other IDE like Eclipse . We are using Scanner class to get input from user.We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement:

 Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream.

Here is the program:

import java.util.Scanner;
public class Inputuser {

  
    public static void main(String args[])  {
    
System.out.println("Enter first number ");
    
 Scanner input = new Scanner(System.in);
    
int a = input.nextInt();
        \
 System.out.println("Enter second number ");
      
 int b = input.nextInt();

       if(a>b)
{
System.out.println("A is greater");
}
else
System.out.println("B is greater");

}     
}

In Scanner class we use some methods to input the user:

1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string


Like the Post? Do share with your Friends.

No comments:

Post a Comment

IconIconIconFollow Me on Pinterest

Blogger news

Blogroll

What's Hot