← All lessons
Java basics · Lesson 9 of 10

Input and errors

Programs get more interesting when someone can type into them. A Scanner reads what's typed at the keyboard. You make one at the start of main and ask it for the next line or the next number:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("What's your name? ");
        String name = in.nextLine();
        System.out.print("How old are you? ");
        int age = in.nextInt();
        System.out.println("Hi " + name + ", next year you'll be " + (age + 1));
    }
}
Terminal
$ java Main.java
What's your name? Ana
How old are you? 12
Hi Ana, next year you'll be 13

import java.util.Scanner; at the top tells Java where to find Scanner, since it isn't built into every file. nextLine() reads everything up to Enter as a String, nextInt() reads a whole number and nextDouble() a decimal. If someone types twelve where a number is expected, the program stops with an error; checking input is a later topic.

Two kinds of error

Everyone's code has mistakes, all the time. The skill is reading what Java tells you. There are two kinds:

  • Compile errors: the compiler finds a problem before anything runs, like a missing ;, a misspelled name or a type that doesn't fit. Nothing runs until you fix them.
  • Runtime errors (Java calls them exceptions): the code compiled, but something went wrong while it ran, like dividing by zero or an index past the end of an array. The program stops at that line.

A compile error names the file, the line and the problem, with a ^ under the spot. Start with the first error: one mistake often causes several messages after it.

Terminal
$ javac Main.java
Main.java:4: error: ';' expected
        int total = 5
                     ^
Main.java:5: error: cannot find symbol
        System.out.println(totl);
                           ^
  symbol:   variable totl
  location: class Main
2 errors

Line 4 is missing its semicolon. On line 5, "cannot find symbol" means Java doesn't know the name totl: it's a typo for total. That one message covers misspelled variables, methods and a missing import.

A runtime error prints the exception's name, a message and a stack trace: the line it happened on, then the lines that called it. The top line inside your own code is usually where to look.

Terminal
$ java Main.java
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.average(Main.java:3)
	at Main.main(Main.java:8)

Read it as: dividing by zero, in the method average at line 3 of Main.java, which was called from main at line 8. The exceptions you'll meet most as a beginner:

  • ArithmeticException: / by zero: a whole number divided by 0.
  • ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException: an index past the end.
  • NullPointerException: using a variable that holds null (nothing) as if it held an object.
  • InputMismatchException: the Scanner wanted a number and got something else.
  • NumberFormatException: turning text that isn't a number into one, like Integer.parseInt("abc").

Finding bugs

The worst bugs give no error at all: the program runs and prints the wrong answer. Then work like a detective. Say what you expected, find the first place where reality differs, and print the values on the way to see where they go wrong:

Java
int[] prices = {4, 6, 10};
int total = 0;
for (int i = 1; i < prices.length; i++) {
    System.out.println("i=" + i + " total=" + total);
    total += prices[i];
}
System.out.println(total);
Prints
i=1 total=0
i=2 total=6
16

The total should be 20, and the printed lines show why: i starts at 1, so the first price is never added. The fix is int i = 0. Delete the debugging print once you've found the cause.

Change one thing at a time and run again. And read the error message all the way through, slowly; it says more than it looks like at first.

Practice

The compiler says error: ';' expected. What's wrong?

More info

Quick reference

Scanner in = new Scanner(System.in);Read from the keyboard (import java.util.Scanner).
in.nextLine() / nextInt() / nextDouble()A line of text / a whole number / a decimal.
compile errorFound before running: fix it and compile again.
exceptionAn error while running; the program stops at that line.
stack traceThe "at" lines: where it happened, then who called it.
cannot find symbolJava doesn't know the name: a typo, scope or a missing import.
Integer.parseInt(s)Turn text into an int; NumberFormatException if it isn't one.

Related courses