import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author gtowell * An example of using Throw to make the handling of exceptions * someone else's problem * Created: Jan 20, 2020 */ public class NameAndAge { /** Holds a persons name */ private String name; /** Holds a persons age */ private int age; /** * Get a persons name and age from the given input stream (which really should * be System.in) * * @param inStream the input stream to read for answers * @throws IOException * @throws NumberFormatException */ public void getNameAndAge(InputStream inStream) throws IOException, NumberFormatException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter student name: "); name = br.readLine().trim(); // gets rid of whitespace at both ends of the string. In this case, CR-LF System.out.print("Enter Age: "); age = Integer.parseInt(br.readLine()); // translate the string read fromt eh keyboard into an integer. } public static void main(String[] args) { // since getNameAndAge Throw exceptions, those exception must be handled here // (Or thrown on further, but there is nowhere further ...) try { NameAndAge nameAndAge = new NameAndAge(); nameAndAge.getNameAndAge(System.in); System.out.println("\n" + nameAndAge); } catch (IOException ioe) { System.err.println("problem " + ioe); } catch (NumberFormatException nfe) { System.err.println("problem " + nfe); } } }