Skip to content
wannacode

Input and output

Problem

The program knows only one name

The program greets the customer by name:

String name = "Maria";
System.out.println("Hello, " + name + "!");
Output
Hello, Maria!

It works, but it greets everyone as Maria. The name is written in the code. For every new customer you have to change the program and run it again. You want the program to ask on its own.

The idea

Reading from the keyboard

When the program reads, it stops and waits. The person types and presses Enter. What they type is the program's input.

Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("What is your name? ");
String name = in.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Input
Maria
Output
What is your name? Hello, Maria!

In Java there is a helper for reading: Scanner. The line import java.util.Scanner; at the top says where it comes from. Scanner in = new Scanner(System.in); creates it and connects it to the keyboard (System.in). Then in.nextLine() reads one line, up to Enter.

Scanner is an object, and new creates an object. You will learn what they mean in the "Classes and objects" module. For now these two lines are part of the wrapper of every program that reads. Later in the lessons we do not show the import line.

The input and the output are shown separately here. In the console the name appears where you type it: after "What is your name? ". That is why the question uses print: so the answer is on the same line.

More precisely, if you are curious
  • One Scanner is enough for the whole program. Create it once, at the start.

Problem

12 + 30 = 1230

The cashier enters two payments, €12 and €30. The program has to show the total:

Scanner in = new Scanner(System.in);
String first = in.nextLine();
String second = in.nextLine();
String total = first + second;
System.out.println("Total: €" + total);
Input
12
30
Output
Total: €1230

Instead of 42 you got 1230. The program did not get the math wrong. It did no math at all.

The idea

From text to a number

Whatever the person types, nextLine() returns text. "12" and "30" are two texts, and + between texts glues them together. To do math, turn the text into a number:

Scanner in = new Scanner(System.in);
int first = Integer.parseInt(in.nextLine());
int second = Integer.parseInt(in.nextLine());
int total = first + second;
System.out.println("Total: €" + total);
Input
12
30
Output
Total: €42

Turning text into a value of another type is called parsing.

  • Integer.parseInt(...) gives an int.
  • Double.parseDouble(...) gives a double.
  • The other types have the same: Long.parseLong, Boolean.parseBoolean and so on.

The sum here is the first calculation in the course. Subtraction, multiplication and division come in the next lesson.

Scanner in = new Scanner(System.in);
int first = Integer.parseInt(in.nextLine());
int second = Integer.parseInt(in.nextLine());
int total = first + second;
System.out.println("Total: €" + total);
Step by step, in words
  1. The person types 12 and Enter. nextLine() returns the text "12", not a number.
  2. Integer.parseInt turns the text into the number 12. It goes into first.
  3. 30 takes the same path: text, parsing, a number in second.
  4. Now + adds numbers: 12 + 30 = 42.
  5. It prints "Total: €42".

Scanner can also read a number directly: in.nextInt() or in.nextDouble(). Then the numbers can also be on one line, separated by a space:

Scanner in = new Scanner(System.in);
int first = in.nextInt();
int second = in.nextInt();
int total = first + second;
System.out.println("Total: €" + total);
More precisely, if you are curious
  • If the text is not a number (for example "twelve"), the program stops with an error: NumberFormatException. You will see how to catch such an error in the "Errors and exceptions" module.
  • A trap: nextInt() reads the number, but not the Enter after it. The next nextLine() reads the rest of the same line, which is empty text:
Scanner in = new Scanner(System.in);
int age = in.nextInt();
String name = in.nextLine();
System.out.println("Name: [" + name + "]");
Input
19
Maria
Output
Name: []

The name is empty. That is why in this course we read lines with nextLine() and convert them with Integer.parseInt. If you use nextInt(), put an empty in.nextLine(); before the next time you read text.

  • The decimal separator depends on the computer's regional settings. Double.parseDouble always wants a point: 3.5. But in.nextDouble() follows the settings, and on a computer with Bulgarian settings it wants a comma: 3,5. The examples in this course use a point.

Try it

How many tickets?

The program reads how many adults and how many children there are.

Input
2
3

What will the program print?

Scanner in = new Scanner(System.in);
int adults = Integer.parseInt(in.nextLine());
int children = Integer.parseInt(in.nextLine());
System.out.println("Tickets: " + adults + children);
Answer

The idea

Numbers the way you want them

In the last lesson the price 49.90 came out as 49.9. For a price you always want two digits after the decimal point. This is formatted output:

String product = "Headphones";
double price = 49.9;
int qty = 2;
System.out.printf("%s: €%.2f%n", product, price);
System.out.printf("%d in the cart%n", qty);
String label = String.format("Price: €%.2f", price);
System.out.println(label);
Output
Headphones: €49.90
2 in the cart
Price: €49.90

printf prints text with placeholders for values. Each placeholder starts with %, and the values come after the text, in the same order:

  • %s is text, %d is a whole number;
  • %.2f is a decimal number with exactly 2 digits after the point;
  • %n is a new line (printf does not move to a new line by itself).

String.format does the same, but it does not print. It returns the text. You can store it in a variable.

The value in the variable does not change. The format only decides how it looks when it is printed.

More precisely, if you are curious
  • Thousands separators and lining up in columns:
double total = 1234.5;
System.out.printf("Total: €%,.2f%n", total);
System.out.printf("%-10s|%8.2f%n", "Coffee", 2.5);
System.out.printf("%-10s|%8.2f%n", "Laptop", 1299.0);
Output
Total: €1,234.50
Coffee | 2.50
Laptop | 1299.00

, adds a thousands separator. The number between % and the letter is the width: %8.2f takes 8 characters, aligned right, and %-10s takes 10, aligned left.

  • Regional settings matter here too. On a computer with Bulgarian settings, %.2f gives 49,90, and the thousands separator is a space: 1 234,50. The output in the lessons uses a point.

Try it

Two digits

A night at the hotel costs €65.5. You want it to come out as "Per night: €65.50". What goes in the blank?

System.out.printf("Per night: €%n", price);

Try it

Find the bug

The program asks how many tickets to reserve. It does not compile. Which line is the bug on?

Pick the line with the bug.

Exercise

Programs that ask

Solve the tasks in your editor. The input is one line for each value. Do not print questions like "Enter a name:", so your output matches the sample.

1. Greeting by name. Read a name and greet the person.

Input
Maria
Output
Hello, Maria!

2. Sum of two numbers. Read two whole numbers and print the calculation.

Input
17
25
Output
17 + 25 = 42

3. Two texts in one. Read two texts and print them together, with a space between them.

Input
Veliko
Tarnovo
Output
Veliko Tarnovo

4. π with two digits. Store π in a variable as 3.14159265358979 and print it with two digits after the point. The ready value Math.PI comes in the next lesson.

Output
3.14

More tasks

  • Age. Read a name and an age (a whole number) and print "Maria is 19 years old."
  • A business card from the keyboard. Read a name, a job and a phone number and print the business card from the "Your first program" lesson with them.
  • A price with two digits. Read a price as a decimal number and print it with two digits and the euro sign: for input 7.5 the output is Price: €7.50.
  • Sum of two prices. Read two decimal prices and print their sum with two digits: for input 12.4 and 3.15 the output is Total: €15.55.

Test

Check yourself

1. What does in.nextLine() return?
2. You read the texts "12" and "30". What does first + second give?
3. What does Integer.parseInt("25") do?
4. int a = 2; int b = 3; What does "Sum: " + a + b print?
5. How do you print 7.5 as 7.50?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·