1.4 Getting User Input

Though many things were designed to work in a straight forward manner in Processing, reading primitive types and Strings from the keyboard was not one of them. Because of the graphical nature of Processing it was designed to have interaction mainly using the mouse (which Processing makes fairly easy). It is also fairly easy to get individual keystrokes from the keyboard. However to read ints and Strings etc. we will need some help.

Download the file Input.pde. Open up a new blank Processing document. Go to Sketch->Add File.. in the menu.

Choose the file you just downloaded. There will now be 2 tabs with Input.pde being visible.

Select the other tab and you can type in your program there. In order to use the code fromInput.pde in your program you will need to use a method called setup. A method is a subprogram that is used to organize your code into smaller, easier to handle pieces. Other languages will sometimes call methods procedures or functions. Here is an example program that shows you how to use Input.pde.

void setup()
{
   char gender;
   String name = getString("Enter your name:");
   int age = getInt("Enter your age");
   float money = getFloat("How much money do you have?");
   gender = getChar("Enter gender (m = male, f= female)");
   print("Hello " + name + ".  You are " + age);
   print(" years old and you have $" + money + "!  Your");
   println(" gender is " + gender + ".");
} 

Notice how the first line of the program is:

void setup()

This is the heading for the setup method. Everything between the matching set of brace brackets is part of that method. Setup is a predefined Processing method that will always get executed one time at the beginning of a Processing program. To get input from the user you call methods from Input.pde. The method names all start wwith the word get followed by the type you want the user to enter. In the brackets after the method you put a String that you want to use as a prompt for the input. When you can one of these methods the prompt will appear in the output area at the bottom of the editor window and a separate dialog box will appear to allow the user to type their input. Whatever is typed will appear in the output area and be stored in the variable used in the method call.

Exercise 1.4

  1. Write an interactive program that prompts the user for their given and family names. It should then print a message welcoming them.
  2. Write an interactive program that prompts the user for some personal data. The program should prompt the user for their name, their age in years, their height in centimetres (to the nearest centimetre), their weight in kilograms (to the nearest tenth of a kilogram), and their sex. The program should then print the personal data in a neat, easily read form.