Console application in Java 7 in netbeans 7.4 – Scanner object

In this post I describe how create console application in Java with Scanner object.

First create project ScannerApp. Choose from menu File->New Project.

In New Project window select from Categories Java and from Projects select Java Application. Click on Next button.

In Project Name field write ScannerApp and click on Finish button.

You see tree of your project in Projects windows in IDE.

If You open source file ( main class ) You see this code:

In main method paste this code:

Scanner in = new Scanner (System.in);
System.out.println("Adding two numbers.");

System.out.println("Write first number:");
int first_number = in.nextInt();
System.out.println("Write second number:");
int second_number = in.nextInt();

System.out.println(first_number+" + "+second_number+" = "+(first_number+second_number));

Right click on Scanner object to import package java.util where is implemented this class. From list of elements select Fix Imports.

You see dialog window in which You click on OK button.

Scanner object allow You to get chars writing in console. As parameter in Scanner constructor You must in this case to pass InputStream object. System.in return this object.

Method nextInt() return int writing in console.

Run Your application clicking on green icon in top of IDE.

You see in console window it:

You click on next line and write first number and click Enter key, then second number. Application display You result from added these numbers and stop its work.

You may either write all numbers with spaces. Change your code in main method:

Scanner in = new Scanner (System.in);
System.out.println("Adding two numbers.");
System.out.println("Write two numbers:");
int first_number = in.nextInt();
int second_number = in.nextInt();System.out.println(first_number+" + "+second_number+" = "+(first_number+second_number));

It will be your result after run application: