Home > Tutorial > Java Command Line Input Example

Java Command Line Input Example

Starting in Java 1.5, you can use the Java Scanner class to read in user typed input from the command line. The scanner class has methods to read in all of the Java primitive data types.

The Scanner will split the command line input into tokens. The delimiter by default is white space. If the user inputs “Fred Flinstone” when prompted for name, you would need to call next() twice to capture both first and last name.


Create Instance Scanner Object

The first step to read in command line input from user is to create a new instance of the Java Scanner class and provide System.in as the argument.

//Create Scanner object to read command line input
Scanner jcdScanner = new Scanner(System.in);


Read Strings From Command Line

The most common method of reading user input from command line is a String or just plain text. The Scanner.next() method will capture and store the user entered String from the command line.

//Prompt User For Float
System.out.println("\nEnter Name:");

//Capture The Integer From User 
String jcdString = jcdScanner.next();

//Respond Back To User
System.out.println("Your Name: "+jcdString);
Enter Name:
JavaCodeDepot
Your Name: JavaCodeDepot


Read Integer From Command Line

The Scanner.nextInt() method will capture and store the user entered Integer from the command line.

//Prompt User For Integer
System.out.println("Enter Integer:");
		
//Capture The Integer From User 
int jcdInteger = jcdScanner.nextInt();
        
//Respond Back To User 
System.out.println("Your Integer:"+jcdInteger);
Enter Integer:
10000
Your Integer: 10000


Read Float From Command Line

The Scanner.nextFloat() method will capture and store the user entered Integer from the command line.

//Prompt User For Float
System.out.println("\nEnter Float:");
		
//Capture The Integer From User 
float jcdFloat = jcdScanner.nextFloat();
		
//Respond Back To User 
System.out.println("Your Float:"+jcdFloat);
Enter Float:
2.345678
Your Float: 2.345678



Concluding Comments

If your Java program needs to interact with the user through the command line, the Java Scanner Class is ideal for capturing user input.



Java References:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot