---
title: "Input | FiveStudy"
description: "The Scanner pipeline: input is a queue, each call consumes the next piece, in order."
url: https://fivestudy.com/guides/input
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Input

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Using Objects and Methods

AP® Computer Science A · Using Objects and Methods

# Input: *Getting Data Into Programs*

The forms input can take, how programs follow an input-process-output pattern, how the Scanner class reads typed text, what happens when input is not what the program expects, and why computation should be kept separate from input.

1. Why Programs Need Input 2. Forms of Input 3. Input, Process, Output 4. Reading Text With Scanner 5. Unexpected Input 6. Designing Around Input

Big Picture

A program that always uses the same values always produces the same results. **Input** lets a program work with new data each time it runs: a different bill to split, a different word to look up, a different photo to analyze. Input can come in a variety of forms, such as tactile, audio, visual, or text. For text typed at a keyboard, the `Scanner` class is one way to obtain input in Java. Whatever its source, good design treats input as data that arrives from outside the program, keeps it separate from the computation, and plans for values that are not what was expected.

## 1 Why Programs Need Input

Compare two programs that compute a tip. The first contains `double bill = 48.0;` and always reports the tip for 48 dollars. The second asks the user for the bill amount and reports the tip for whatever amount is entered. The second is far more useful, because its behavior depends on data that is not known when the program is written.

Input is what connects a program to the world: the person using it, the sensors on a device, the files stored on a computer, or other programs sending data. Every app you use reacts to input constantly, from the letters you type to the location reported by your phone. Learning to think about where data comes from, what form it arrives in, and how to turn it into values the program can use is a central part of programming.

While developing and testing a program, though, fixed values are extremely useful. A computation tested with values whose correct results you know, like a bill of 48 and a tip of 20 percent, can be checked quickly and repeatably. Many programs are written first with fixed values and only later connected to real input.

## 2 Forms of Input

Input can come in a variety of forms. **Tactile** input comes from touch and movement: buttons, touchscreens, game controllers, and keyboards in the physical sense. **Audio** input comes from sound captured by microphones, such as voice commands. **Visual** input comes from light: cameras, barcode scanners, and image recognition. **Text** input is made of characters, typically typed by a user or read from a file.

Hardware and libraries convert each of these into data a program can process. A voice assistant may turn speech into text before the main program sees it; a barcode scanner turns a pattern of stripes into a product number. By the time the input reaches the code that uses it, it is usually a number, a string, or a `boolean`, the same kinds of values the program already works with.

**Figure 1.** Input can come in a variety of forms, such as tactile, audio, visual, or text. Whatever its form, a program receives it as data to work with.

| Form of input | Examples | What the program receives |
| --- | --- | --- |
| Tactile | Touchscreen taps, button presses, joystick movement | Positions, pressed/not pressed, directions |
| Audio | Voice commands, recorded sound | Sound data, or text produced by speech recognition |
| Visual | Camera images, barcode scans | Image data, or decoded values such as a product code |
| Text | Typing on a keyboard, form fields | Characters, which may be converted to numbers |

Worked Example 1 Forms of input

### Classifying Everyday Input

Classify the form of input in each situation.

1. A player tilts and taps a game controller.
2. A smart speaker responds to "set a timer for ten minutes."
3. A grocery checkout reads a barcode with a laser scanner.
4. A student types a search phrase into a library website.
5. A phone unlocks by recognizing its owner's face.
1. 1 **1: Tactile.** Physical touch and movement.
2. 2 **2: Audio.** Sound captured by a microphone.
3. 3 **3: Visual.** A pattern of light captured by a sensor.
4. 4 **4: Text.** Characters typed on a keyboard.
5. 5 **5: Visual.** An image from a camera.

**Result:** The forms are tactile, audio, visual, text, and visual. In every case, the device converts the input into data that a program processes.

## 3 The Input-Process-Output Pattern

Most programs follow a simple pattern: get **input**, **process** it, and produce **output**. Planning a program in these three parts clarifies what information is needed, what must be computed, and what the user should see. For a tip calculator, the input is the bill and the percentage, the processing is one multiplication and one division, and the output is the labelled tip amount.

Thinking this way also reveals the data types involved. A bill amount has cents, so it is a `double`; a percentage chosen from whole numbers is an `int`. Deciding types at the planning stage determines which input methods the program will use and how the arithmetic must be written to avoid integer division.

**Figure 2.** Most programs follow an input-process-output pattern. Input lets the same program work with different data each time it runs.

Worked Example 2 Program design

### Planning a Tip Calculator

Describe the input, processing, and output for a program that computes a tip, then write the processing with fixed test values.

Code

```
double bill = 48.0;
int percent = 20;
double tip = bill * percent / 100.0;
System.out.println("Tip: " + tip);
```

Output

```
Tip: 9.6
```

1. 1 **Input.** The bill amount (a `double`) and the tip percentage (an `int`).
2. 2 **Process.** Multiply the bill by the percentage and divide by `100.0`; the `.0` keeps the division real.
3. 3 **Output.** A labelled tip amount.
4. 4 **Test first with fixed values.** Using known values (48.0 and 20 give 9.6) checks the computation before any input code is written.

**Result:** The computation prints `Tip: 9.6`. Planning input, process, and output separately makes the program easier to build and test.

## 4 Reading Text With a Scanner

The `Scanner` class is one way to obtain text input from the keyboard. A program creates a `Scanner` object connected to the keyboard with `new Scanner(System.in)`, after an `import java.util.Scanner;` line at the top of the file makes the class available. The program then calls methods on that object to read values.

A `Scanner` treats typed text as a sequence of **tokens**: groups of characters separated by spaces or line breaks. Methods such as `nextInt`, `nextDouble`, `nextBoolean`, and `next` each skip any separators and read the next token, converting it to the requested type. `nextLine` works differently: it reads everything up to the end of the current line, spaces included. Because the two styles treat line breaks differently, a program should use one style consistently for a given input source rather than mixing them.

When a program waits for input, it pauses at the reading statement until the user types something and presses Enter. That is why a **prompt**, an output statement telling the user what to type, should come before each read.

**Figure 3.** A `Scanner` breaks typed text into tokens. Each call to a method such as `nextInt` reads the next token and converts it to the requested type.

| Scanner method | Reads | Example typed token → value |
| --- | --- | --- |
| `nextInt()` | The next token as an `int` | `42` → 42 |
| `nextDouble()` | The next token as a `double` | `3.75` → 3.75 |
| `nextBoolean()` | The next token as a `boolean` | `true` → true |
| `next()` | The next token as a `String` | `Kestrel` → "Kestrel" |
| `nextLine()` | The rest of the current line as a `String` | `blue whale` → "blue whale" |

Worked Example 3 Reading text input

### Reading Two Numbers With a Scanner

When the user types `12 30` and presses Enter, what does this program print?

Code

```
Scanner input = new Scanner(System.in);
System.out.println("Enter two whole numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println("Sum: " + (a + b));
```

Output

```
Enter two whole numbers:
Sum: 42
```

1. 1 **Create the Scanner.** `new Scanner(System.in)` connects a `Scanner` object to keyboard input. The `import` line at the top of the file makes the `Scanner` class available.
2. 2 **Prompt.** The program tells the user what to type before waiting for input.
3. 3 **Read tokens.** The first `nextInt` reads 12; the second skips the space and reads 30 (Figure 3).
4. 4 **Process and output.** The sum 42 is displayed with a label.

**Result:** With input `12 30`, the program prints the prompt and then `Sum: 42`. The typed text itself also appears on screen as the user types it.

Worked Example 4 Reading different types

### A Word and a Decimal Number

The user types `Kestrel 72.5`. Predict the output.

Code

```
Scanner input = new Scanner(System.in);
String name = input.next();
double weight = input.nextDouble();
System.out.println(name + " weighs " + weight + " kg");
```

Output

```
Kestrel weighs 72.5 kg
```

1. 1 **`next()`** reads one token as a `String`: "Kestrel".
2. 2 **`nextDouble()`** reads the next token and converts it to a `double`: 72.5.
3. 3 **Match the method to the type.** Each reading method expects a particular kind of token; choosing the right one is part of designing the input.

**Result:** The program prints `Kestrel weighs 72.5 kg`. Different `Scanner` methods read different types of values.

Common Mistake 1 · Forgetting the Prompt

Without a prompt, a program that is waiting for input looks frozen: the cursor blinks and nothing happens. Always print a short message saying what to enter and in what form, such as "Enter your age in whole years:", immediately before reading.

## 5 When Input Is Not What You Expected

Input comes from outside the program, so it can be wrong in ways the code cannot control. A user can type a word where a number was expected, add an extra space, or leave a field blank. If `nextInt` finds a token that is not an integer, it throws an `InputMismatchException`, a run-time error that stops the program.

Robust programs reduce these problems with clear prompts and, in more advanced code, by checking input before converting it. At this stage, the key habit is awareness: whenever a program reads input, ask what would happen if the value were missing, out of range, or of the wrong type.

Worked Example 5 Unexpected input

### When the User Types the Wrong Kind of Value

The program expects a number, but the user types `ten`. Predict what happens.

Code

```
Scanner input = new Scanner(System.in);
System.out.println("How many tickets?");
int tickets = input.nextInt();
System.out.println("Total: " + tickets * 12);
```

1. 1 **The prompt prints.** Everything before the read runs normally.
2. 2 **`nextInt` cannot convert "ten".** The token is not an integer, so the method throws an `InputMismatchException`, a run-time error that stops the program.
3. 3 **Design lesson.** Input comes from outside the program and cannot be trusted to have the expected form. Clear prompts help, and more advanced programs check input before converting it.

**Result:** The program prints the prompt and then stops with an `InputMismatchException`. Programs that read input must plan for values that do not match what they expect.

Common Mistake 2 · Assuming Users Type Exactly What You Intended

Programs often work perfectly for the programmer, who knows exactly what to type, and fail for everyone else. Test input-reading code with unexpected entries: words instead of numbers, decimals instead of whole numbers, zero, negative values. Each surprising result points to a prompt that needs to be clearer or a check that needs to be added.

## 6 Designing Around Input

A well-designed program keeps input separate from computation. The input section reads values and stores them in clearly named variables; the processing section, ideally a method with parameters, computes results from those values without knowing where they came from. This separation has three benefits: the computation can be tested with fixed values in seconds, the same computation can be reused with a different input source such as a file, and bugs are easier to locate because input problems and logic problems live in different places.

Input also does not have to come from a person. Programs read data from files, sensors, and networks, and the same design principles apply. Later work with files uses a `Scanner` connected to a file instead of the keyboard, and the processing code does not need to change at all.

**Figure 4.** Keeping input separate from computation lets the computation be written as a method that receives values as parameters, so it can be tested quickly and reused with any source of data.

| Design choice | Why it helps |
| --- | --- |
| Print a prompt before every read | The user knows what to type and in what form |
| Read each value into a well-named variable | The rest of the program can use clear names, not raw input |
| Keep calculations in separate methods | Computations can be tested with fixed values |
| Use one reading style per input source | Mixing line-based and token-based reading on the same source causes confusing results |

Worked Example 6 Separating input

### A Computation That Does Not Depend on the Keyboard

Rewrite the tip computation as a method that receives its values as parameters, then test it with several fixed inputs.

Code

```
public static double tip(double bill, int percent)
{
    return bill * percent / 100.0;
}
```

Output

```
9.6
1.5
0.0
```

1. 1 **The method only computes.** It does not care whether its values came from a keyboard, a file, a sensor, or a test.
2. 2 **Testing is instant.** Three calls with known answers check the logic without typing anything: 9.6, 1.5, and 0.0.
3. 3 **Any input source can use it.** A keyboard version would read `bill` and `percent` with a `Scanner` and then call `tip(bill, percent)`.

**Result:** The tests print 9.6, 1.5, and 0.0. Separating input from processing, as in Figure 4, makes programs easier to test and to reuse.

Common Mistake 3 · Mixing Input Code Into Every Calculation

When reading statements are scattered through the calculations, every test requires typing values by hand, and a change in the input source means rewriting the whole program. Read all input first, store it in variables, and pass those values to the code that computes.

Common Mistake 4 · Mixing Line-Based and Token-Based Reading

Token methods such as `nextInt` stop right after the token they read, leaving the rest of the line, including its line break, unread. A following `nextLine` then returns that leftover part, often an empty string, instead of the next line the user types. Choose one reading style for each input source and use it consistently.

### Four Habits for Working With Input

#### 1. Plan Input, Process, Output

Decide what data comes in, what is computed, and what is shown.

#### 2. Prompt Before Reading

Tell the user exactly what to type.

#### 3. Match Method to Type

nextInt for int, nextDouble for double, next for a word.

#### 4. Keep Computation Separate

Test calculations with fixed values before connecting real input.

Core Synthesis

Input can come in a variety of forms, such as tactile, audio, visual, or text, and in every case it becomes data that a program processes. Programs commonly follow an input-process-output pattern. The `Scanner` class is one way to obtain text input from the keyboard: it reads typed text as tokens and converts them with methods such as `nextInt`, `nextDouble`, and `next`. Input that does not match what a program expects can cause run-time errors, so good programs use clear prompts and keep input separate from computation, which also makes the computation easy to test.

FiveStudy AP® Computer Science A Study Guide · Using Objects and Methods · Input Back to top ↑
