Getting User Input

The majority of programs today require user interaction or user input. A television runs a program that receives a user’s input through a remote control. A bank ATM also receives user’s input through a number pad. Also your cellphone / laptop have several programs that receive your input through a keyboard. As you can see, the ability to receive input is extremely important for programs.

keyboard

To setup your program to receive user input from a keyboard you should do 2 things;

  1. Put this line of code in your program:
    Scanner input = new Scanner(System.in);
  2. Then put input.next(); in parts of your code where you want the user to enter something with their keyboard.
    • ex. String data = input.next();
      *this will get only one word at a time. If the input is “hello my world”, only hello will be taken
  • To get the an entire line/sentence use input.nextLine();
    • ex. String data = input.nextLine();   – *this will get the entire line of input
  • You must use input.nextInt(); or input.nextDouble(); to get numeric input.

Ex.1

Ex.2

Fill in the blanks

double myNumber =
String mySentence =
int myNumber2 =
input.next… should never come before Scanner input = new Scanner(System.in); in your code.
You must create the Scanner before you can use it.

Program -> write a program that gets the users name and two numbers, the program must multiply the two numbers and then print an output similar to the following: Hello Albert, 3 X 2 = 6

Back to Course Menu
What do you think about this topic? Share your suggestions / comments