×

java · level 1 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

String.format fills in the gaps in your text.

String.format works like a birthday card with gaps. Write the text with a in each gap: %s for a string, %d for a whole number. Then list the values to drop in, in order.

System.out.printf does the same job and prints straight away. It stays on the line like print, so put %n at the end to move to a new line.

Remember, nextLine() always gives back text. To do maths with it, it first. Integer.parseInt("12") turns the text "12" into the int 12.

public class Main {
    public static void main(String[] args) {
        String name = "Sam";
        int age = 9;
        System.out.println(String.format("Happy birthday, %s! You are %d.", name, age));
        System.out.printf("Next year you will be %d.%n", age + 1);
        int candles = Integer.parseInt("9");
        System.out.println(candles + 1);
    }
}

Integer.parseInt only works on text that looks like a whole number, so "cake" gives an error.