嘿我的java程序里面有一个扫描器类,它不会读取文件。它给了我以下例外" DayCalParser.java:21:错误:未报告的异常FileNotFoundException;必须被抓住或宣布被扔掉#34; 我想我应该使用某种IOexception,但不知道放在哪里,因为这只是一个类而且没有主要的方法。
我也收到一条错误,说没有找到退货声明
import java.util.*;
import java.io.*;
import java.lang.*;
public class DayCalParser {
private int i = 0;
private String userdate = "";
private Scanner scan = new Scanner(System.in);
private int day = scan.nextInt();
private int fday;
Scanner fileScan = new Scanner(new File("cal.txt"));
private ArrayList < String > dates = new ArrayList < String > ();
private void datesFinder(int fday) throws IOException {
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
if (line.contains("DTSTART")) {
if (line.length() > 25) {
String year = line.substring(19, 23);
String month = line.substring(23, 25);
String dayofmonth = line.substring(25, 27);
userdate = (dayofmonth + "/" + month + "/" + year);
}
}
if (line.contains("SUMMARY")) {
String summary = line.substring(12, 13);
if (summary.equals(fday)) {
i = i + 1;
dates.add(userdate);
}
}
} //while
}
public String getDates(int fday) {
datesFinder(fday);
for (int j = 0; j < dates.size(); j++) {
String a = dates.get(j);
return a;
}
}
}
答案 0 :(得分:0)
它不是异常,而是编译错误。 Scanner
的构造函数抛出FileNotFoundException
。
在DayCalParser
构造函数
public DayCalParser() throws FileNotFoundException {
fileScan = new Scanner(new File("cal.txt"));
}
另外,请将getDates()
修改为:
public String getDates(int fday) throws IOException {
datesFinder(fday);
for (int j = 0; j < dates.size(); j++) {
String a = dates.get(j);
return a;
}
return null;
}
答案 1 :(得分:0)
你可以查看下面的代码,同时修改getDates()函数,你可以通过任何类调用该函数。
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main {
private int i = 0;
private String userdate = "";
private Scanner scan = new Scanner (System.in);
private int day = scan.nextInt();
private int fday;
private ArrayList<String> dates = new ArrayList<String>();
private void datesFinder(int fday) throws IOException, FileNotFoundException {
Scanner fileScan = new Scanner(new File("cal.txt"));
while (fileScan.hasNext()){
String line = fileScan.nextLine();
if (line.contains("DTSTART")){
if (line.length()>25){
String year = line.substring(19,23);
String month = line.substring(23,25);
String dayofmonth = line.substring(25,27);
userdate = (dayofmonth + "/" + month + "/" + year);
}
}
if (line.contains("SUMMARY")) {
String summary = line.substring(12,13);
if (summary.equals(fday)){
i = i+1;
dates.add(userdate);
}
}
}//while
}
public String getDates(int fday){
try {
datesFinder(fday);
for(int j = 0; j < dates.size(); j++) {
String a = dates.get(j);
return a;
}
}catch (IOException e){
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Main obj = new Main();
obj.getDates((int) (new Date().getTime()/1000));
}
}