How Do You Write a Java Program to Accept a Number for the Command Terminal and Print It Back Out?

Problem scenario
You want to write a basic Java program to test it out.  How do you write a program to accept user input, specifically a number, and print it back to the screen (using the integer data type)?

Solution
1.  Install the Java Development Kit if you have not installed it yet.  If you are not sure you have it, run javac -version.  If it says that the command is not found, you need to install the Java Development Kit.  If you do not know how, see this posting.

2.  Create this file named acceptNum.java:

import java.util.Scanner;

public class acceptNum {

public static void main(String[] args) {
   System.out.println("Please enter an integer, then press enter: ");
   Scanner in = new Scanner(System.in);
   int num = in.nextInt();
   System.out.println(num);
  }
 }

3.  Run this command: javac acceptNum.java

4.  Run this command: java acceptNum

If you want to purchase a book on Java, click here

Leave a comment

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