Static Counter
Completed
Create Ticket with a static int nextId so every new ticket gets the next id, starting at 1. Read names and print #id name for each, then the total number created.
Input
n, then n names.
Output
n + 1 lines.
Example
Input
3 ann bob cy
Output
#1 ann #2 bob #3 cy 3
Editor
Java
Hints
A static field is shared by all objects of the class.
nextId++ uses the value, then increments it.
Solution explanation
Static fields belong to the class itself, not to each object.
Show solution
import java.util.Scanner;
class Ticket {
static int nextId = 1;
final int id;
final String name;
Ticket(String name) {
this.id = nextId++;
this.name = name;
}
@Override
public String toString() {
return "#" + id + " " + name;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Ticket.nextId = 1;
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(new Ticket(sc.next()));
}
System.out.println(Ticket.nextId - 1);
}
}