Lesson 1.2
Statements run top to bottom
Part 1: Programs that talkReading, about 3 min2 exercises in this lesson
Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.
Instructions run from top to bottom
By the end of this you will be able to write a program that prints several lines in the order you want, including an empty line.
A program with more than one instruction runs them one after another, starting at the top. The computer finishes one instruction before it starts the next. So the order you write your instructions in is the order things happen.
Several lines, in order
Each print instruction prints one line, and the lines come out in the order the instructions are written.
print("Doors closing.")
print("Going down.")
print()
print("Ground floor.")public class Main {
public static void main(String[] args) {
System.out.println("Doors closing.");
System.out.println("Going down.");
System.out.println();
System.out.println("Ground floor.");
}
}When it runs, the screen shows:
Doors closing. Going down. Ground floor.
The third instruction has nothing between its brackets, so it prints an empty line: a line with nothing on it. That is how a program leaves a gap between parts of what it prints.
Order matters
Swap the first two instructions, and the first two lines swap to match:
Going down. Doors closing.
The computer does not know which message makes sense first. It only follows your instructions, one by one, from the top.
A common mistake: writing the right lines in the wrong order, then reading your own output too quickly to notice. When your program prints something different from the question, compare the two line by line, starting with the first.
Now try it yourself on the questions below.
Exercise 1.2.11.2.1 · Write itDoor messages
A lift shows three messages, one after another. Write a program that prints exactly these three lines, in this order:
Going up. Next stop: floor 4. Mind the doors.
- Each message is on its own line, and the lines come in the order shown.
- Everything is checked exactly: capitals, spaces, the colon and the full stops. Spaces at the end of a line are ignored.
- Print nothing else.
The program reads no input. In Python, write one instruction for each line. In Java, the page starts you with a class and its main method: write your instructions between the braces of main, and print with System.out.println.
Running Java here comes later. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
Examples
Your program is run once, as in the example below. Only what it prints is checked.
the three lines, in order (rules 1 to 3)
You type
Nothing
It prints
Going up. Next stop: floor 4. Mind the doors.