Getting User Input in Java

While Java provides many different methods for getting user input, the Scanner object is the most common, and perhaps the easiest to implement. Import the Scanner class to use the Scanner object, as seen here:

import java.util.Scanner; 

In order to use the Scanner class, create an instance of the class by using the following syntax:

Scanner input = new Scanner(System.in);

You can now read in different kinds of input data that the user enters.
Here are some methods that are available through the Scanner class:

1. Read a byte – nextByte()
2. Read a short – nextShort()
3. Read an int – nextInt()
4. Read a long – nextLong()
5. Read a float – nextFloat()
6. Read a double – nextDouble()
7. Read a boolean – nextBoolean()
8. Read a complete line – nextLine()
9. Read a word – next()

Example of a program used to get user input:

 

import java.util.Scanner;

public class UserInputDemo {
  public static void main(String[ ] args) {
  Scanner input = new Scanner(System.in);
  int age=sc.nextInt();
  double salary=sc.nextDouble()
  System.out.println("Age is:"+age); 
  System.out.println("Salary is:"+salary);
}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s