CSERD


  • userhome
  • catalog
  • resources
  • help

Programming in Java


Shodor > CSERD > Resources > Tutorials > Programming in Java

  Intro  •   Lesson 1  •   Lesson 2  •   Lesson 3  •   Lesson 4  •   Lesson 5  •   Final Challenge


Programming in Java - Lesson 5

Input/Output

Some languages are designed to make input as simple as possible. Java isn't one of them. However, in this lesson we will provide you with a few simple routines to help you handle Input/Output (IO) in Java.

In most computer languages, you have three I/O (input/output) streams that can be accessed. There is the standard input stream, the standard output stream, and the standard error stream. You can also open files for reading and writing in most languages. This is true in Java as well, though file access can get complicated in applets or networked programs.

You have already used the standard output stream, and its most commonly used method, println.

Unfortunately, standard input does not have a "readln" command.

What Standard input does have is the read command, which reads characters from standard input into an array of bytes. This array of bytes can then be turned into a java String, and you can use the many methods available for Strings to further access the input data.

Let's start with something simple. How would you go about creating a "readln" command?

Consider the following program.

//------------------------------------------
// IO.java, test methods of getting user
//    input.
//------------------------------------------

public class IO {
    public static void main(String [] args) {
        String lineIn = readLn();
        System.out.println(lineIn);
    }

    // read a line of input from standard input
    public static String readLn() {
        //set aside memory for the keyboard input
        byte [] byteArray = new byte[300];
        
        //things which could fail should be enclosed
        // in a try/catch statement
        try {
            // read stdin into the byte array.
            System.in.read(byteArray);
        } catch (Exception e) {
            // if there is a failure, print an error
            e.printStackTrace();
        }
        
        //make a String from the array of bytes
        String result = new String(byteArray);

        //check for a return character, and only
        //keep the characters up to the return
        int newLineIndex = result.indexOf("\n");
        if (newLineIndex>-1)
            result = result.substring(0,newLineIndex);
        newLineIndex = result.indexOf("\r");
        if (newLineIndex>-1)
            result = result.substring(0,newLineIndex);
        
        return result;
    }
}

Notice that as usual, we keep the main routine as simple as usual by putting repetitive tasks into a function call, readLn.

readLn sets aside memory for the user input. This is stored in a list of bytes, called an array. An array is just a list of values of a given data type. It s accessed by the number of a piece of data in the list (the first element is number 0, not 1). For an array of bytes holding the phrase byteArray="Hello World", byteArray[0] is "H", byteArray[1] is "e", and so on.

To set aside the memory for this array we must "instantiate it", or create an instance of it. We use the new keyword to do this. Basically, we define byteArray to be an array of bytes (byte [] byteArray) and tell the computer that when it gets to that line, create the new array (bytearray = new byte[300]).

A problem could occur here if the user inputs more than 300 characters, but for this case we won't worry about it. We then read in the input from the keyboard, but since this is an action which can have an error (the fancy word for this is that it throws an exception) we enclose the action in a try/catch statement. Some statements in Java actually require that they be enclosed in a try/catch statement.

The String class in java is used to store text. String has an array of characters, and also has a number of functions (or methods) to manipulate that data.

Notice that we use the new keyword again here. new can be used to create an array, but it can also be used to create an instance of a class. Here we define result to be a String, and set result equal to a new instance of a String, which is created from the data in byteArray.

We search for a newline character using the String method indexOf, and take a substring of the original which only includes that data up to the newline character.

That value is then returned.

Challenge problem

Write a routine which reads a double value from the command line. Include graceful error checking.


©1994-2024 Shodor