Java Input/Output  «Prev   Next»

Read from Standard Input - Exercise

Write a stand-alone, character-mode program


Write a stand-alone, character-mode program that reads from the standard input into a StringBuffer object.
Here is what your program should do:
  1. Ask the user to enter a number.
  2. Read this number from the standard input, appending characters to a StringBuffer object, until the user presses Enter.
  3. Invoke the StringBuffer's toString() method to get a String object from the StringBuffer object.
  4. Convert this character string into a number using a wrapper data type. For example, you can convert a String object to an int by writing:
    int i = new Integer(s).intValue()
    
  5. Test to see if this number is a prime. A prime numbers is not evenly divisible by any numbers between 2 and itself minus 1. You can use the % operator to calculate the remainder of a division.
  6. Write a message indicating whether the number is a prime.

Handling exceptions is optional, but it's always a good idea to do so.
Once you have this working, copy and paste your answer into the text area below.