Programs become useful when they accept input from the user. Java reads keyboard input with the Scanner class. This chapter also covers comments and the kinds of errors you'll meet (ICSE Class 9).
1Ways to give data & the Scanner class
Data can reach a program three ways: by initialisation (fixed in the code), as parameters (passed in), or by run-time input (typed while it runs). For run-time input, Java uses Scanner, which lives in the java.util package — so you import it first:
import java.util.Scanner; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // a whole number double d = sc.nextDouble(); // a decimal String w = sc.next(); // a single word String line = sc.nextLine(); // a whole line char c = sc.next().charAt(0); // a single character
| Method | Reads |
|---|---|
nextInt() / nextShort() / nextLong() | Whole numbers |
nextFloat() / nextDouble() | Decimal numbers |
next() | One word |
nextLine() | A whole line of text |
- Data reaches a program by initialisation, parameters, or run-time input.
- Scanner (from java.util — must be imported) reads keyboard input.
- Methods: nextInt/nextDouble (numbers), next() (a word), nextLine() (a line), next().charAt(0) (a character).
2Comments & output statements
Comments are notes for humans; Java ignores them. Use them to explain code:
// a single-line comment /* a multi-line comment */
print vs println
| Statement | Does |
|---|---|
System.out.print(x) | Prints x and stays on the SAME line |
System.out.println(x) | Prints x and moves to a NEW line |
System.out.print("Hello ");
System.out.println("World"); // Hello World, then newline
- Comments are ignored by Java: // for single-line, /* ... */ for multi-line.
- System.out.print(x) prints and stays on the same line.
- System.out.println(x) prints and moves to a new line (ln = line).
3Types of errors
Programs can have three kinds of error (bug):
| Error | What it is | Example |
|---|---|---|
| Syntax error | Breaks the grammar rules of Java — caught by the compiler | Missing semicolon, misspelt keyword |
| Runtime error | Happens WHILE the program runs and crashes it | Dividing by zero |
| Logical error | Program runs but gives the WRONG answer | Using + where you meant * |
- Syntax errors break Java's grammar and are caught by the compiler (e.g. missing semicolon).
- Runtime errors crash the program while it runs (e.g. divide by zero).
- Logical errors let the program run but give the wrong answer — the hardest to find.
★ Practical: read and respond
In BlueJ, write programs that:
- Read your name (a word) and age (an int) with Scanner and greet you.
- Read two doubles and print their average.
- Use both print and println to show the difference on screen.
- Add a single-line and a multi-line comment explaining your code.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.