How Do You Write a Java Program to Read in Letters and Numbers?

Problem scenario
You want to create a basic Java program that can read alphanumeric input interactively. How do you write such a program?

Solution
1. Verify the "javac" command works. Run "man javac" to see the man page. If you do not get a man page, install the Java development tools. On a RedHat derivative, run this: sudo yum -y install java-devel

2. Create a contint.java file with the content below. Use the usage instructions in the header comments.

/* This program was written by continualintegraiton.com
You should call it contint.java.  compile it with "javac contint.java" and run the byte code with "java contint"
It shows how to read in letters and numbers into a Java program */

import java.util.Scanner;

public class contint{
    public static void main(String args[]){
    System.out.println("Enter some characters and press enter:");

    Scanner ascanitem= new Scanner(System.in);
    String secondpart= ascanitem.nextLine();
    System.out.println(secondpart);
    System.out.println(" ");
    System.out.println("Enter some numbers and press enter");
    int number= ascanitem.nextInt();
    System.out.println(number);
    }
}

3. Run these commands:
javac contint.java
java contint

Leave a comment

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