The line with "private static BufferedReader" is where the problem lies. "-unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" is the error. Here is my current code:
import java.io.*;
import java.util.*;
public class PG2ERC
{
private static ArrayList<Integer> arl = new ArrayList<Integer>();
private static BufferedReader br = new BufferedReader(new FileReader("pageRefString.txt"));
public static void main(String[] args) throws IOException, FileNotFoundException
{
String [] arr;
int n1 = 3;
int n2 = 4;
int f;
int pf1 = 0;
int pf2 = 0;
arr = br.readLine().split(" ");
for(String s:arr)
{
f=Integer.parseInt(s);
if(arl.contains(f))
{
arl.remove(arl.indexOf(f));
arl.add(f);
}
else if(arl.size() < n1)
{
++pf1;
arl.add(f);
}
else
{
arl.remove(0);
arl.add(f);
++pf1;
}
f=Integer.parseInt(s);
if(arl.contains(f))
{
arl.remove(arl.indexOf(f));
arl.add(f);
}
else if(arl.size() < n2)
{
++pf2;
arl.add(f);
}
else
{
arl.remove(0);
arl.add(f);
++pf2;
}
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("pg2out.txt"))))
{
writer.write(("Number of page faults is ") + pf1);
writer.write(("Number of page faults is ") + pf2);
}
}
}
}
The problem is more simply demonstrated like this:
import java.io.*;
class Test {
private static Reader reader = new FileReader("foo.txt");
}
The problem is that the static initializer for your class can throw an exception. That's entirely separate to your main
method.
Now in your case, the simplest solution is to change your fields to local variables:
// No need to declare FileNotFoundException - it's a subclass of IOException anyway
public static void main(String[] args) throws IOException
{
ArrayList<Integer> arl = new ArrayList<Integer>();
BufferedReader br = new BufferedReader(new FileReader("pageRefString.txt"));
... rest of method as before ...
}
At that point, the code that can throw an exception is within a method that declares that those exceptions can be thrown, so it's fine.
If you do need to initialize static variables like this, you should do so in a static initializer block:
private static BufferedReader br;
static {
try {
br = new BufferedReader(new FileReader("pageRefString.txt"));
} catch (IOException e) {
// Go bang hard - RuntimeException isn't a checked exception
throw new RuntimeException(e);
}
}
See more on this question at Stackoverflow