java · level 1 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two gaps, two values. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
String food = "chips";
String drink = "lemonade";
System.out.println(String.format("I would like %s with %s.", drink, food));
}
}
your turn
Your turn. Fill in the birthday card.
Type a name between the quotes on line 3 and an age, as a whole number, on line 4. Then press run.
output
press run to see what happens
fix it
Dog years went wrong. Can you fix it?
output
press run to see what happens
- Java will not multiply on line 7. What type is the box called age?
nextLine()gives back text, and you cannot multiply text. Convert it into anintfirst.- Change line 6 to
int age = Integer.parseInt(keyboard.nextLine());, then press run.
nailed it
your text fills itself in now. :D
%sand%dsave spots for values inString.format.- The values fill the gaps in order.
Integer.parseIntturns typed text into a whole number.
new words in your collection
- placeholder
- convert
This lesson isn’t saved. A free account remembers every lesson you finish.