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.
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.
1Why 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.
2Forms 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.
| 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 |
Classifying Everyday Input
Classify the form of input in each situation.
- A player tilts and taps a game controller.
- A smart speaker responds to "set a timer for ten minutes."
- A grocery checkout reads a barcode with a laser scanner.
- A student types a search phrase into a library website.
- A phone unlocks by recognizing its owner's face.
- 11: Tactile. Physical touch and movement.
- 22: Audio. Sound captured by a microphone.
- 33: Visual. A pattern of light captured by a sensor.
- 44: Text. Characters typed on a keyboard.
- 55: Visual. An image from a camera.
3The 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.
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.
double bill = 48.0;
int percent = 20;
double tip = bill * percent / 100.0;
System.out.println("Tip: " + tip);
Tip: 9.6
- 1Input. The bill amount (a
double) and the tip percentage (anint). - 2Process. Multiply the bill by the percentage and divide by
100.0; the.0keeps the division real. - 3Output. A labelled tip amount.
- 4Test first with fixed values. Using known values (48.0 and 20 give 9.6) checks the computation before any input code is written.
Tip: 9.6. Planning input, process, and output separately makes the program easier to build and test.4Reading 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.
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" |
Reading Two Numbers With a Scanner
When the user types 12 30 and presses Enter, what does this program print?
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));
Enter two whole numbers:
Sum: 42
- 1Create the Scanner.
new Scanner(System.in)connects aScannerobject to keyboard input. Theimportline at the top of the file makes theScannerclass available. - 2Prompt. The program tells the user what to type before waiting for input.
- 3Read tokens. The first
nextIntreads 12; the second skips the space and reads 30 (Figure 3). - 4Process and output. The sum 42 is displayed with a label.
12 30, the program prints the prompt and then Sum: 42. The typed text itself also appears on screen as the user types it.A Word and a Decimal Number
The user types Kestrel 72.5. Predict the output.
Scanner input = new Scanner(System.in);
String name = input.next();
double weight = input.nextDouble();
System.out.println(name + " weighs " + weight + " kg");
Kestrel weighs 72.5 kg
- 1
next()reads one token as aString: "Kestrel". - 2
nextDouble()reads the next token and converts it to adouble: 72.5. - 3Match the method to the type. Each reading method expects a particular kind of token; choosing the right one is part of designing the input.
Kestrel weighs 72.5 kg. Different Scanner methods read different types of values.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.
5When 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.
When the User Types the Wrong Kind of Value
The program expects a number, but the user types ten. Predict what happens.
Scanner input = new Scanner(System.in);
System.out.println("How many tickets?");
int tickets = input.nextInt();
System.out.println("Total: " + tickets * 12);
- 1The prompt prints. Everything before the read runs normally.
- 2
nextIntcannot convert "ten". The token is not an integer, so the method throws anInputMismatchException, a run-time error that stops the program. - 3Design 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.
InputMismatchException. Programs that read input must plan for values that do not match what they expect.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.
6Designing 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.
| 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 |
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.
public static double tip(double bill, int percent)
{
return bill * percent / 100.0;
}
9.6
1.5
0.0
- 1The method only computes. It does not care whether its values came from a keyboard, a file, a sensor, or a test.
- 2Testing is instant. Three calls with known answers check the logic without typing anything: 9.6, 1.5, and 0.0.
- 3Any input source can use it. A keyboard version would read
billandpercentwith aScannerand then calltip(bill, percent).
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.
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.
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.