-3

here is my code

package test.program;
/**
 *
 * @author Justin 
*/

public class TestProgram 
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
       char ch;
       ch = (char)System.in.read();
       if(ch<'K')
           System.out.println("This stuff is less than K " + ch);
       else
           System.out.println("Thats that stuff I don't like " + ch);
    }

}

am I forgetting to import something? It gives me an error saying

unreported exception IOException, must be caught or declared to be thrown

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77

4 Answers4

4

System.in is an InputStream, and InputStream's read method throws an IOException.

Throws:

IOException - if an I/O error occurs.

It's a checked exception, so you must catch it or have the method that calls it declare that it throws IOException.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

This part works ch = (char)System.in.read();. Your problem is elsewhere.
It is that the main method does not declare to throw IOException.

Try this:

public static void main(String[] args) throws java.io.IOException {

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

When you're working with IO in Java, most of the times you have to handle the IOException. It can occur when you're reading the input, in this case.

Try like this:

public static void main(String[] args) 
{
   char ch;
   try{
       ch = (char)System.in.read();
   }
   catch(IOException e){
       e.printStackTrace();
   }
   if(ch<'K')
       System.out.println("This shit is less than K " + ch);
   else
       System.out.println("Thats that shit I don't like " + ch);
}
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
0

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read() - From API, the read() method of InputStream throws IOException, hence you either need to catch it or rethrow it

user1339772
  • 783
  • 5
  • 19