import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.Scanner; /** * A simple example of constructors, reading from the keyboard and toString * Created: Jan 15, 2020 Modified: Jan 22, 2020 * * @author gtowell */ public class Student { /* The name of the student */ String name; /* The Age of the student */ int age; /** * Ensures that the instances variables are * initialized */ public Student() { name = ""; age = 0; } /** * Construct a Student instance with both name and age * * @param n the name * @param a the age */ public Student(String n, int a) { name = n; age = a; } /** * Construct a Student instance by getting input from the given stream * * @param inStream -- the stream from which to get student information. This is * expected to be System.in * @throws IOException * @throws NumberFormatException */ public Student(InputStream inStream) throws IOException, InputMismatchException { this(); // call the default constructor to be sure that the variables are initialized Scanner scanner = new Scanner(inStream); System.out.print("Enter student name: "); name = scanner.nextLine(); System.out.print("Enter Age: "); age = scanner.nextInt(); } /** * The standard toString method. But it has a typo (extra g) so it won't get * called automatically * * @return A string representation of a student */ @Override public String toString() { StringBuilder sb = new StringBuilder("Details.............."); sb.append("\n Name: ").append(this.name).append("\n Age: ").append(age); return sb.toString(); } /** * One version of getting input from the user. * * @param args ignored */ public static void main(String[] args) { try { Student student = new Student(System.in); System.out.println("\n" + student); } catch (IOException ioe) { System.err.println("problem " + ioe); } catch (InputMismatchException ime) { System.err.println("problem224 " + ime.toString()); } } public static void main2(String[] args) { Scanner scanner = new Scanner(System.in); String name; int age; System.out.print("Enter student name: "); name = scanner.nextLine(); try { System.out.print("Enter Age: "); age = scanner.nextInt(); } catch (InputMismatchException e) { System.err.println("problem " + e); return; } Student student = new Student(name, age); System.out.println("\n" + student.toString()); } }