[英]I get the error: posible loss of of precision and i have tried to change it but I can fix it, please help me
[英]Throw error. How can I fix this? I've tried many things, but I am new to it and the logic is a little beyond me
问题所在是带有“ private static BufferedReader”的行。 错误是“-未报告的异常java.io.FileNotFoundException;必须捕获或声明为抛出”。 这是我当前的代码:
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);
}
}
}
}
该问题更简单地显示为:
import java.io.*;
class Test {
private static Reader reader = new FileReader("foo.txt");
}
问题是您的类的静态初始化器可能引发异常。 这与您的main
方法完全分开。
现在,根据您的情况,最简单的解决方案是将字段更改为局部变量:
// 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 ...
}
那时,可以引发异常的代码在声明可以引发这些异常的方法之内,所以很好。
如果确实需要像这样初始化静态变量,则应在静态初始化程序块中进行初始化:
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);
}
}
在main
方法之外,将BufferedReader
静态变量设置为null。 并在main
方法中初始化将解决此问题。
private static BufferedReader br = null;
public static void main(String[] args) throws IOException, FileNotFoundException
{
br = new BufferedReader(new FileReader("pageRefString.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.