User Input

You can request input from the user using the read functions. You need to use a different function depending on the type of the data you want to read. There are five options:

  • readInt()
  • readDouble()
  • readString()
  • readChar()
  • read()
  • isEOF()
  • int a;
    a = readInt();
    println( a );
    

    readInt() will read the first integer number on the input stream. Whitespace is ignored, and all consecutive digits are read to form the integer.

    If you give a non-integer number to a readInt() call then it will be truncated (not rounded) i.e. 4.8 will be truncated to 4. If you give non-numerical input (e.g. a string) then a message "unable to read integer" will appear and readInt() will return the value zero.

    String s;
    s = readString();
    println( s );
    

    With the current implementation, the string input routine will pick up the first whole word on the input stream. Two words typed will be picked up by different calls of readString(). Words can contain or end with numbers but cannot start with a digit. If a number is given to a readString() call then a message "unable to read string" will be displayed and the function will return null. N.B. null is not the same as the empty string "".

    char c;
    c = readChar();
    println( c ); 
    

    readChar() returns the first available non-whitespace character on the input. It will pick up control characters like carriage return.

    read() returns the very next available character on the input stream regardless of whether it is whitespace, a letter, digit, control character etc.

    isEOF() returns true if the EOF has been reached or false otherwise.

    int a;
    while (! isEOF() ) {
    	a = readInt();
    	println("You entered : "+a);
    }
    println("Finished");