Number the Lines
Problem
Print every input line with its line number in front: three digits (with leading zeros), then the character |, then the original line. Blank lines are counted and printed too (as number and |). Do not change the text of the line.
Constraints
- 1 <= lines <= 999
Examples
Input
alpha gamma
Output
001|alpha 002| 003|gamma
Solutions
The position in the input gives the number. A format string pads it with zeros. The line text itself is copied without trimming.
/*
* Problem : Number the lines.
* Input : Several lines (blank lines allowed).
* Output : Numbered lines.
* Approach: Format each line.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
// Step 1: Count lines from 1 and format the number with three digits.
String[] output = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
output[i] = String.format("%03d|%s", i + 1, lines[i]);
}
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
all.add(scanner.nextLine());
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (2)
- What does %03d do?
- Why must blank lines keep their number?