1
import java.io.*;

public class prelab7 {

   public static void readstring(String a){

    String s = "EECS 132";

    StringReader s1 = new StringReader(s);
    for (int n = 0; n < s.length(); n = n + 1){

        char c = (char)s1. read();
        System.out.print(" " + c);
    }
  }
}

1 error found: File: /Users/clara/Desktop/EECS132/prelab7.java [line: 8] Error: /Users/clara/Desktop/EECS132/prelab7.java:8: unreported exception java.io.IOException; must be caught or declared to be thrown

user3353820
  • 83
  • 1
  • 1
  • 6
  • Read and then post the entire error message. – Blorgbeard Feb 26 '14 at 01:25
  • Is it your IDE that's complaining or the compiler? Anyway `read()` throws an `IOException` (or something similar) which must be caught in your code. – rath Feb 26 '14 at 01:27
  • 1
    [The Catch or Specify Requirement](http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html) – Radiodef Feb 26 '14 at 01:27

1 Answers1

2

A StringReader is a Reader. And a Reader's .read() method can throw an IOException.

You need to change your method declaration to:

public static void readstring(String a)
    throws IOException
{
    // code here
}

(edit: or use try/catch, as mentioned in comments; if you do so however, please avoid the classical .printStackTrace() with nothing else)

fge
  • 119,121
  • 33
  • 254
  • 329
  • @OP, For example, what if the file "EECS 132" doesn't exist? The Reader will throw an exception. – user949300 Feb 26 '14 at 01:30
  • @user949300 well, here, it is barely a `String` so it doesn't really matter... Note that if we really wanted to be pedantic, we could also mention that a `Reader` is a `Closeable`, and as such you should systematically `.close()` it... – fge Feb 26 '14 at 01:33
  • Good point - I misread the code slightly too... Make that "what if `s` were an empty string?" – user949300 Feb 26 '14 at 01:37