InvalidUserInputException

hey folks,
I am studying the Horton's Java 2 and experiencing an error in chapter 13:
the compiler says the InvalidUserInputException is never thrown in body of my try statement. But I have the in.readInt() which might throw this error. I have the readInt() defined in class "FormattedInput".
I will copy paste the code for the PhoneNumber.java and then FormattedInput.java.
please help me find what is wrong here. Thanks.
import java.io.*;
import java.util.*;
class PhoneNumber implements Serializable{
    public void addEntry(BookEntry entry){
        phonebook.put(entry.getPerson(), entry);
    public BookEntry getEntry(Person key){
        return(BookEntry)phonebook.get(key);
    public PhoneNumber getNumber(Person key){
        return getEntry(key).getNumber();
    private HashMap phonebook = new HashMap();
    public static PhoneNumber readNumber(){
        FormattedInput in = new FormattedInput();
        int maxTries = 5;
        String area = null;
        String localcode = null;
        for (;;){
            try{
                if (area == null){
                    System.out.println("\nEnter the area code: ");
                    area =  Integer.toString(in.readInt());
                if (localcode == null){
                    System.out.println("Enter the local code:");
                    localcode =  Integer.toString(in.readInt());
                System.out.println("Enter the number:");
                String code =  Integer.toString(in.readInt());
                localcode += " " + code;
                return new PhoneNumber(area, localcode);
            }catch(InvalidUserInputException e){
                if (--maxTries == 0){
                    System.out.println("Maximum number of errors exeeded Termination!");
                    System.exit(1);
                System.err.println(e.getMessage() + "\nTry again");
                continue;
    public PhoneNumber(String areacode, String number){
        this.areacode = areacode;
        this.number = number;
    public String toString(){
        return areacode + ' ' + number;
    private String areacode;
    private String number;
and now the FormattedInput.java :
import java.io.*;
public class FormattedInput {
  public int readInt() {
    try {
      for(int i = 0; i < 5; i++) {
        if(tokenizer.nextToken() == tokenizer.TT_NUMBER && tokenizer.nval == (double)((long) tokenizer.nval))
          return (int)tokenizer.nval;
        else {
          System.out.println("Incorrect input: " + tokenizer.sval +
                             " Re-enter an integer");
          continue;
      System.out.println("Five failures reading an int value" + " - program terminated");
      System.exit(1);
      return 0;
    } catch(IOException e) {
      System.out.println(e);
      System.exit(1);
      return 0;
  public String readString() {
    try {
      for(int i = 0; i < 5; i++) {
        int tokenType = tokenizer.nextToken();
        if(tokenType==tokenizer.TT_WORD || tokenType == '\"' || tokenType == '\'') return tokenizer.sval;
        else if(tokenType == '!')
          return "!";
        else {
          System.out.println("Incorrect input. Re-enter a string, please.");
          continue;
      System.out.println("Five failures reading a string" + " - program terminated");
      System.exit(1);
      return null;
    } catch(IOException e) {
      System.out.println(e);
      System.exit(1);
      return null;
  private StreamTokenizer tokenizer = new StreamTokenizer(new InputStreamReader(System.in));
}

Your FormatedInput methods don't throw any InvalidUserInputException
You are also handling the input errors two times once in FormattedInput.java
and in PhoneNumber.java
change it to something like this:
public class FormattedInput {
  public int readInt()
     throws InvalidUserInputException
    try {
        if(tokenizer.nextToken() == tokenizer.TT_NUMBER && tokenizer.nval == (double)((long) tokenizer.nval))
          return (int)tokenizer.nval;
        else {
          // the error handling is done by PhoneNumber which cathes this exception
          throw new InvalidUserInputException("Incorrect input: " + tokenizer.sval +
                             " Re-enter an integer");
    } catch(IOException e) {
      System.out.println(e);
      System.exit(1);
      return 0;
  public String readString()
    throws InvalidUserInputException
    try {
        int tokenType =  tokenizer.nextToken();
        if(tokenType==tokenizer.TT_WORD || tokenType == '\"' || tokenType == '\'') return tokenizer.sval;
        else if(tokenType == '!')
          return "!";
        else {
          // the error handling is done by PhoneNumber which catches this exception
          throw new InvalidUserInputException("Incorrect input. Re-enter a string, please.");
    } catch(IOException e) {
      System.out.println(e);
      System.exit(1);
      return null;
  private StreamTokenizer tokenizer = new StreamTokenizer(new InputStreamReader(System.in));

Similar Messages

  • HELP Can you see the missing parenthesis ?!

    Dear People,
    I am doing a simple program that creates a ContactBook and allows keyboard entry of lastName, telephoneNumber and emailAddress.
    I have a few error messages that say parenthesis missing but I don't
    see any missing ! :
    "Note.java": Error #: 200 : '{' expected at line 15
    "Note.java": Error #: 200 : '}' expected at line 59
    "TryContactBook.java": Error #: 200 : ')' expected at line 30
    "TryContactBook.java": Error #: 200 : ')' expected at line 42
    below is the coding
    thank you in advance
    Stan
    import java.util.*;
    public class TryContactBook
       private Note note;
       public static void main(String[] args)
         ContactBook myContactBook = new ContactBook();
         FormattedInput input = new FormattedInput();
         Note note = new Note();
         System.out.println("Enter the number of new notes you wish to record ");
         int numberOfNotes = input.readInt();
         System.out.println("Ready to record " + numberOfNotes + "note(s) ");
         for (int i = 0; i < numberOfNotes; i++)
           try
             System.out.print("Enter a last name: ");
              note.setLastNaame(input.readString());
             System.out.println("last name input is: " + notes.getLastName());
           catch (InvalidUserInputException e)
              System.out.println("InvalidUserInputException thrown when inputting last name. \n" +
                         e.getMessage());
            try
               System.out.println("Enter a telephone number ");
              note.setTelephoneNumber(input.readString();
             System.out.println("telephone number input is: " + notes.getTelephoneNumber());
           catch (InvalidUserInputException e)
              System.out.println("InvalidUserInputException thrown when inputting last name. \n" +
                         e.getMessage());
            try
              System.out.println("Enter an e-mail address ");
              note.setTelephoneNumber(input.readString();
              System.out.println("e-mail address  input is: " + notes.getEmailAddress());
            catch (InvalidUserInputException e)
              System.out.println("InvalidUserInputException thrown when inputting last name. \n" +
              e.getMessage());
    =====================================================================
    import java.util.*;
    * A class to maintain an arbitrarily long list of contacts.
    * Notes are numbered for external reference by a human user.
    * In this version, note numbers start at 0.
    * @author Stan Dominski
    public class ContactBook
        // Storage for an arbitrary number of notes.
        private ArrayList notes;
         * Perform any initialization that is required for the
         * notebook.
        public ContactBook()
            notes = new ArrayList();
         * Store a new note into the notebook.
         * @param note The note to be stored.
        public void storeNote(String note)
            notes.add(note);
         * @return The number of notes currently in the notebook.
        public int numberOfNotes()
            return notes.size();
         * Show a note.
         * @param noteNumber The number of the note to be shown.
        public void showNote(int noteNumber)
            if(noteNumber < 0 || noteNumber > numberOfNotes())
                // This is not a valid note number, so do nothing.
            else
                // This is a valid note number, so we can print it.
                System.out.println(notes.get(noteNumber));
         * Remove a note from the notebook if it exists.
         * @param noteNumber The number of the note to be removed.
        public void removeNote(int noteNumber)
           if(noteNumber < 0 || noteNumber > numberOfNotes())
           System.out.println("noteNumber is not valid.");
           else
            notes.remove(noteNumber);
          * List all the notes in the notebook
           public void listNotes()
              Iterator i = notes.iterator();
               Iterator myIterator = notes.iterator();
              while(i.hasNext() && myIterator.hasNext())
                 System.out.print(notes.indexOf(i.next() ) + ":" );
                 System.out.println("" + myIterator.next());
    =======================================================================
    import java.util.*;
    public class Note
       private ArrayList contactInfo;
       private String lastName;
       private String telephoneNumber;
       private String emailAddress;
       public class Note()
            contactInfo = new ArrayList();
           this.lastName = lastName;
          this.telephoneNumber = telephoneNumber;
          this.emailAddress = emailAddress;
        public  void setLastName(String lastName)
           this.lastName = lastName;
              public String getLastName()
                 return lastName;
                    public  void setTelephoneNumber(String telephoneNumber)
                       this.telephoneNumnber = telephoneNumber;
              public String getTelephoneNumber()
                 return telephoneNumber;
                    public  void setEmailAddress(String emailAddress)
                        this.emailAddress = emailAddress;
                  public String getEmailAddress()
                     return emailAddress;
    ======================================================================
    import java.io.*;
    import java.util.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    public class FormattedInput
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. ..... Input data is not a string");
         // Method to read an int value
    public int readInt() throws InvalidUserInputException
       if (readToken() != tokenizer.TT_NUMBER)
         throw new InvalidUserInputException(" readInt() failed. " + " input data not numeric");
       else
         return (int)tokenizer.nval;   // value is numeric so return as int
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    ======================================================================
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);

    I have out comments on the errors I found. There might be more.
    I couldn't get the indentation to work so it will look a bit funny.
    //David
    "Note.java": Error #: 200 : '{' expected at line 15
    "Note.java": Error #: 200 : '}' expected at line 59
    "TryContactBook.java": Error #: 200 : ')' expected at
    line 30
    "TryContactBook.java": Error #: 200 : ')' expected at
    line 42
    import java.util.*;
    public class TryContactBook
    private Note note;
    public static void main(String[] args)
    ContactBook myContactBook = new ContactBook();
    FormattedInput input = new FormattedInput();
    Note note = new Note();
    System.out.println("Enter the number of new notes you wish to record ");
    int numberOfNotes = input.readInt();
    System.out.println("Ready to record " + numberOfNotes + "note(s) ");
    for (int i = 0; i < numberOfNotes; i++)
    try
    System.out.print("Enter a last name: ");
    note.setLastNaame(input.readString());
    System.out.println("last name input is: " +
    is: " + notes.getLastName());
    catch (InvalidUserInputException e)
    System.out.println("InvalidUserInputException
    xception thrown when inputting last name. \n" +
    e.getMessage());
    try
    System.out.println("Enter a telephone
    telephone number ");
    note.setTelephoneNumber(input.readString()); // 1 error
    System.out.println("telephone number input
    er input is: " + notes.getTelephoneNumber());
    catch (InvalidUserInputException e)
    System.out.println("InvalidUserInputException
    xception thrown when inputting last name. \n" +
    e.getMessage());
    try
    System.out.println("Enter an e-mail address
    l address ");
    note.setTelephoneNumber(input.readString()); // 2 error
    System.out.println("e-mail address  input
    ss  input is: " + notes.getEmailAddress());
    catch (InvalidUserInputException e)
    System.out.println("InvalidUserInputException
    xception thrown when inputting last name. \n" +
    e.getMessage());
    =======================================================
    =============
    import java.util.*;
    * A class to maintain an arbitrarily long list of
    contacts.
    * Notes are numbered for external reference by a human
    user.
    * In this version, note numbers start at 0.
    * @author Stan Dominski
    public class ContactBook
    // Storage for an arbitrary number of notes.
    private ArrayList notes;
    * Perform any initialization that is required for
    for the
    * notebook.
    public ContactBook()
    notes = new ArrayList();
    * Store a new note into the notebook.
    * @param note The note to be stored.
    public void storeNote(String note)
    notes.add(note);
    * @return The number of notes currently in the
    the notebook.
    public int numberOfNotes()
    return notes.size();
    * Show a note.
    * @param noteNumber The number of the note to be
    o be shown.
    public void showNote(int noteNumber)
    if(noteNumber < 0 || noteNumber >
    umber > numberOfNotes())
    // This is not a valid note number, so do
    mber, so do nothing.
    else
    // This is a valid note number, so we can
    , so we can print it.
    System.out.println(notes.get(noteNumber));
    * Remove a note from the notebook if it exists.
    * @param noteNumber The number of the note to be
    o be removed.
    public void removeNote(int noteNumber)
    if(noteNumber < 0 || noteNumber >
    mber > numberOfNotes())
    System.out.println("noteNumber is not
    is not valid.");
    else
    notes.remove(noteNumber);
    * List all the notes in the notebook
    public void listNotes()
    Iterator i = notes.iterator();
    Iterator myIterator = notes.iterator();
    while(i.hasNext() && myIterator.hasNext())
    System.out.print(notes.indexOf(i.next() )
    f(i.next() ) + ":" );
    System.out.println("" +
    println("" + myIterator.next());
    =======================================================
    ===============
    import java.util.*;
    public class Note
    private ArrayList contactInfo;
    private String lastName;
    private String telephoneNumber;
    private String emailAddress;
    public class Note()
    contactInfo = new ArrayList();
    this.lastName = lastName;
    this.telephoneNumber = telephoneNumber;
    this.emailAddress = emailAddress;
    public  void setLastName(String lastName)
    this.lastName = lastName;
    public String getLastName()
    return lastName;
    public  void setTelephoneNumber(String
    neNumber(String telephoneNumber)
    this.telephoneNumnber =
    telephoneNumnber = telephoneNumber;
    public String getTelephoneNumber()
    return telephoneNumber;
    public  void setEmailAddress(String
    lAddress(String emailAddress)
    this.emailAddress = emailAddress;
    public String getEmailAddress()
    return emailAddress;
    }} // 3 error
    =======================================================
    ==============
    import java.io.*;
    import java.util.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    public class FormattedInput
    public String readString() throws
    rows InvalidUserInputException
    if(readToken() == tokenizer.TT_WORD || ttype ==
    ype == '\"' || ttype == '\'')
    return tokenizer.sval;
    else
    throw new InvalidUserInputException("
    eption(" readString() failed. ..... Input data is not
    a string");
    // Method to read an int value
    public int readInt() throws
    InvalidUserInputException
    if (readToken() != tokenizer.TT_NUMBER)
    throw new InvalidUserInputException(" readInt()
    nt() failed. " + " input data not numeric");
    else
    return (int)tokenizer.nval; // value is numeric
    eric so return as int
    //helper method to read the next token
    private int readToken()
    try
    ttype = tokenizer.nextToken();
    return ttype;
    catch(IOException e)
    e.printStackTrace(System.err);
    System.exit(1);
    return 0;
    //object to tokenize input from the standard
    andard input stream
    private StreamTokenizer tokenizer = new
    = new StreamTokenizer(
    new
    new
    new
    new BufferedReader(
    new
    new
    new
    new
    new
    new
    new
    new InputStreamReader(System.in)));
    private int ttype; //stores
    stores the token type code
    =======================================================
    ==============
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends
    Exception
    public InvalidUserInputException() { }
    public InvalidUserInputException(String
    tring message)
    super(message);

  • What to do when readString() fails and String[] out of bounds ?

    Dear Java People,
    I have a runtime error message that says:
    stan_ch13_page523.InvalidUserInputException: readString() failed. Input data is not a string
    java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    below is the program
    thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = "";
            try
            firstName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
            e.printStackTrace(System.err);
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName= "";
            try
              lastName = in.readString().trim(); //read and trim a string
            catch(InvalidUserInputException e)
             e.printStackTrace(System.err);
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;

    Dear Nasch,
    ttype is declared in the last line of the FormattedInput class
    see below
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i ++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          } // end of for loop
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
             System.out.println(tokenizer.sval);
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
         }

  • Curve 9380: Return from character input to QWERTY keyboard

    Hello,
    I own BlackBerry Curve 9380 smartphone (all touch, without physical keyboard).
    I have the following issue:
    Consider you're writing a text message, when you need a question mark you're tapping on the "&% 123"  button in the left-down corner and selecting the question mark. In order to return back to the original QWERTY keyboard you need to tap on the button again, now "ABC".
    Is that possible to automate the return to the QWERTY keyboard from character input keyboard after tapping the "space" button?
    Keyboard is returning automatically back only if you will tap on the "Enter" button.
    Adding the "space" button would be a great enhancement for touch-based devices featuring BlackBerry 7 OS.
    Thank you.
    P.S. I didn't find any better medium for my concern than this forum, if somebody knows how to reach directly to software engineering group, please let me know.

    You still have the constructor declared inside the main method! :-)
    public class TrySimpleVectorWithKeyboardInput
    public static void main(String[] args)
    public TrySimpleVectorWithKeyboardInput()
    {}Move the two lines to outside the main. It should look something like this..
    import java.util.*;
    import java.io.*;
    public class TrySimpleVectorWithKeyboardInput {
        public TrySimpleVectorWithKeyboardInput() {
          // constructor code goes here
        public static void main(String[] args)    {
            Vector names = new Vector();       
            FormattedInput kb = new FormattedInput();       
            for (int i = 0; i < 5; i++) {         
                try {           
                    System.out.print("Enter a  name ");           
                    names.add( kb.readString());         
                } catch (InvalidUserInputException e) {           
                    System.out.println("InvalidUserInputException thrown. \n" + e.getMessage());         
            System.out.println("\nThe names in the vector are:\n ");       
            Iterator j = names.iterator();       
            while (j.hasNext()) {
                System.out.println(j.next());       
    }

  • Exception must be caught or declared to be thrown?

    got two errors when compling:
    TryCalendar.java [20:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
    int day = in.readInt();
    ^
    TryCalendar.java [21:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
    int month = in.readInt();
    Is there anyone could kindly tell me how to solve? Thank you very much! The short source code as following:
    import java.util.GregorianCalendar;
    import java.text.DateFormatSymbols;
    public class TryCalendar {
    public static void main(String[] args) {
    FormattedInput in = new FormattedInput();
    // Get the date of birth from the keyboard
    System.out.println("Enter your birth date as dd mm yyyy: ");
    int day = in.readInt();
    int month = in.readInt();
    int year = in.readInt();
    // Create birht date calendar - month is 0 to 11
    GregorianCalendar birthdate = new GregorianCalendar(year, month-1, day);
    GregorianCalendar today = new GregorianCalendar(); // Today's date
    // Create this year's birthday
    GregorianCalendar birthday = new GregorianCalendar(
    today.get(today.YEAR),
    birthdate.get(birthdate.MONTH),
    birthdate.get(birthdate.DATE));
    int age = today.get(today.YEAR) - birthdate.get(birthdate.YEAR);
    String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names
    System.out.println("You were born on a " + weekdays[birthdate.get(birthdate.DAY_OF_WEEK)]);
    System.out.println("This year you " + (birthday.after(today) ?"will be " : "are " ) + age + " years old.");
    System.out.println("This year your birthday " + (today.before(birthday)? "will be": "was") + "on a " + weekdays[birthday.get(birthday.DAY_OF_WEEK)]);
    }

    The compiler error has to do with "Exceptions"
    "Exceptions" are things that might go wrong while the program is running. In this case, the user might type "ABC" when the program is trying to read a number using readInt. If the user does this, then that line of code will "throw" an "InvalidUserInputException".
    Your code must "handle" the exception. There are two ways to do this.
    Note that your code is part of a method, namely, the main method
    public static void main(String args[])
      int day = in.readInt(); // Exception might be thrown here
    }   // end of main methodThe first way to deal with the Exception is to decide that main will throw it. Already, readInt throws the Exception to main, now we will make main in turn throw the exception back to whatever called it.
    This can be done as follows. Note the change to the declaration of main.
    public static void main(String args[]) throws InvalidUserInputException
      int day = in.readInt(); // Exception might be thrown here
    }   // end of main methodThen your code should compile and run. This method is not recommended - if the user types in ABC, the program will crash with a cryptic error message.
    It is much better, if readInt throws the Exception, to have your code catch it. To do this, the code that might throw the exception must be contained in a try block, which must be followed by a catch block.
    public static void main(String args[])
      try {
        int day = in.readInt(); // Exception might be thrown here
      } // end of try block
      catch (InvalidUserInputException iue) { 
        ... // code to handle the exception
    }   // end of main methodWhat this means is that java will "try" to perform the code in the try block, and if the user types ABC instead of a number, the InvalidUserInputException thrown by int day=in.readInt() will be "caught", and the code in the catch block will run. The code in the catch block can be anything you like. The most sensible thing to do would be to print some error message informing the user that they typed something wrong. Maybe something like:
       boolean done = false;
       int day,month,year;
       do {
          try {
             System.out.println("Enter your birth date as dd mm yyyy: ");
             day = in.readInt();      // line (1)
             month = in.readInt();    // line (2)
             year = in.readInt();     // line (3)
             done = true;             // line (4)
          catch (InvalidUserInputException iuie) {
             System.out.println("Are you trying to confuse me? I'm only a poor harmless computer! ");       // line (5)
             System.out.println("dd mm and yyyy must be numbers!");
        } while (!done);If an Exception is thrown on lines (1), (2) or (3), then line (4) will not be reached - instead, the program will run from line (5). Since done is still false, the program will loop back to ask for the birthdate again.
    If no exception is thrown, line (4) ensures that the loop will finish, and the catch block is skipped altogether.
    Hope that makes things clearer :-)
    Yours, Mike H...

  • Must be caught or declared to be thrown ! Help !

    Dear Java People,
    I have only one error in my program in the TryVectorAndSort class
    "Unreported exception (InvalidUserInputException)
    Must be caught or declared to be thrown lines 41,49"
    >>    String firstName = in.readString().trim();
    >>     String lastName = in.readString().trim();
    so the error in the above 2 lines points to the readString() method
    which is below
      public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
    below is the entire FormattedInput class
    Thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          }  //end of if statement
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
        } //end of method
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = in.readString().trim(); //read and trim a string
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName = in.readString().trim();    // read and trim a string
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    }

    Dear Levi H,
    When I changed the catch block type to
    String lastName= "";
    try
    lastName = in.readString().trim(); //read and trim a string
    catch(InvalidUserInputException e)
    e.printStackTrace(System.err);
    I no longer have errors in the driver class but in the FormattedInput
    class there are new errors that say:
    "FormattedInput.java": Error #: 204 : illegal start of expression at line 49,68
    "FormattedInput.java": Error #: 206 : malformed expression at line 39,49
    Help !
    Norman

Maybe you are looking for

  • Buyer Beware!! No data plan when using Droid X as a hotspot!!

    I purchased the Droid X right when it came out and got the "unlimited" data and hotspot options.  I just received my first bill and it has $250 worth of data charges on it.  I called customer support and learned that hotspot data is not in the unlimi

  • Invoice Verification Tolerance

    Hi We have setup tolerance Key DW and message M8-088 'GR quantity delivered is ZERO' for POs with GR based IV ticked.. The system issues error even for those POs where GR based IV is not ticked. Any advise on how to configure system to allow Invoice

  • Netscape 7 replaces form window when calling reports

    Netscape 7.0, unlike Netscape 4.7 does not handle forms application that calls on Reports to display Report preview in PDF. When our forms call reports to display a report to the user in the browser, the window on which the form screen is presented i

  • Max. Bildzahl für PS-Album 2.0

    Weiss jemand, wieviel PS Album 2.0 max. bearbeiten kann. Wir haben derzeit damit rund 20 000 Bilddateien gespeichert. Beim Start des Programms kann man sich in Ruhe einen Kaffee bereiten gehen, bis das gesamte Album geladen ist vergehen Minuten, auch

  • 1.1 query builder join between tables

    In the latest Sql Developer. I invoke the query builder and select multiple tables that have foreign keys between them. These foreign key relationships appear in the diagram (good job). How do I make those relationship appear in the SQL that query bu