With a generic lattice model for electrons occupying a semi-infinite crystal with a hard surface, we study the eigenstates of the system with a bulk band gap (or the gap with nodal points). The exact solution to the wave functions of scattering states is obtained. From the scattering states, we derive the criterion for the existence of surface states. The wave functions and the energy of the surface states are then determined. We obtain a connection between the wave functions of the bulk states and the surface states. For electrons in a system with time-reversal symmetry, with this connection, we rigorously prove the correspondence between the change of Kramers degeneracy of the surface states and the bulk time-reversal $Z_2$ invariant. The theory is applicable to systems of (topological) insulators, superconductors, and semi-metals. Examples for solving the edge states of electrons with/without the spin-orbit interactions in graphene with a hard zigzag edge and that in a two-dimensional $d$-wave superconductor with a (1,1) edge are given in appendices.