Tuesday, April 10, 2012

User Input

One of my favorite things to include when writing personal programs is user input. I've used this to make trivia, mad libs, and ASCII art programs. It's pretty straightforward in Python and C++ and a little more complicated in Java. Let's say I want a program that greets a user by name, and maybe some other information like age or location.


name = raw_input("What is your name?")
location = raw_input("Where do you live?")
print "Hello, " + name + " from " + location


int main ()
{
    cout << "What is your name? ";
    cin >> name;
    cout << "Where do you live? ";
    cin << location;
    cout << "Hello, " << name << " from " << location << endl;
}


import java.util.Scanner;

public class UserInputExample {

     public static void main (String[] args) {

        Scanner userInput = new Scanner(System.in);
        System.out.print("What is your name? ");
        name = userInput.next();
        System.out.print("Where do you live? ");
        location = userInput.next();
        System.out.println("Hello, " + name + " from " + location);
    }
}
  • In Python, the optional prompt that is passed to raw_input will be printed on the screen. 
    • This function will wait until it encounters a newline character, and then it will convert whatever was typed by the user into a string.
  • In C++, the cin keyword acts like Python's raw_input, in that it converts whatever is typed into a string.
    • However, cin waits for any whitespace, rather than just a newline character.
    • To avoid this complication, getline can be used.

      cout << "What is your name?"
      getline (cin, name);
    • getline takes whatever is typed until it encounters a newline character, and sets it to the provided variable name.
    • Also, unlike Python, the prompt is not part of cin, so you must include anything you want to ask the user for above the cin line.
  • In Java, we have to import a built in Java class, Scanner, that handles input. 
    • When this class is instantiated, you have to specify that you want user input, by passing System.in to the constructor.
    • Like C++, the prompt and user input are separate.
    • In order to get the input you use Scanner's next() method, which returns input that ends with a delimiter. 
      • The next() method is set to use any whitespace as its default delimiter (meaning it will return the input once it encounters any whitespace), but this can be customized by passing your desired delimiter to the method: userInput.next("\n")