Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Applets
Expertise: Beginner
May 13, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Data input

I need to pass some data from the user to my applet (or application) which is to be entered from the keyboard, using TextField.

The data is repetitive (it fills an array), so when the user enters data for one field of an array, he is to enter another, and another and so on, until all the data is entered. After that, user must enter data from the same TextField into another array, for example, and so on, until everything is known. Because of the amount of data, I can't use parameters in the APPLET tag.

This whole thing should be similar to something like this in C:

   printf("Please enter data");
   printf("Please enter data");

The following code fills a two-dimensional array with numbers read from stdin. The code takes advantage of the fact that Java methods can return arrays as values, hence the line:

 nums[i] = readArray(System.in, M);
can be placed in a loop, and the dirty work of actually reading numbers can be encapsulated inside readArray. The only option remaining was to read an entire line with
This works, but maybe not for long. JDK1.1 declares readLine obsolete. The preferred technique is to use the readLine method of the BufferedReader class:
BufferedReader din = new BufferedReader(new InputStreamReader(in));
   result[i] = din.ReadLine();
Hope this gives you some ideas:
import java.io.*;

public class ReadDemo {

   private static int[] readArray(InputStream in, int m) {

      int[] result = new int[m];
      DataInputStream din = new DataInputStream(in);
      String digits;

      for(int i = 0; i < m; i++) {
         System.out.print("enter a number: ");
         // System.out.flush();
         try {
             digits = din.readLine();
             result[i] = Integer.valueOf(digits).intValue(); 
         catch(IOException e) {
            System.out.println('\n' + e.toString());
      return result;

   public static void main(String[] args) {

      int M = 2, N = 2;
      int[][] nums = new int[N][M];

      for(int i = 0; i < N; i++) 
         nums[i] = readArray(System.in, M);

      System.out.println("Here are your numbers: ");

      for(int j = 0; j < N; j++) {
         for(int k = 0; k < M; k++)
            System.out.print(" " + String.valueOf(nums[j][k]));

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date