如果我修改main方法类,我可以使这段代码工作,但是我应该在不修改它的情况下使它工作。我不知道是什么导致了这个错误。
下面是我在类中编写的方法
public boolean addSongs(String fileName)throws FileNotFoundException
{
Scanner scan = null;
try //open the try block for FNFE
{
//open the file, declare scanner, set endFile to false
scan = new Scanner(new File(fileName));
boolean endFile = false;
while(!endFile) //continues until the end of the file
{
try //try block for mismatch exception or no such element
{
//scan in line and read through it with new delimiter
String line = scan.nextLine();
Scanner read = new Scanner(line);
read.useDelimiter("/");
//scan in name, minutes, and seconds on the scanned line
String scannedName = read.next();
int scannedMin = read.nextInt();
int scannedSec = read.nextInt();
//print the results
System.out.print("Name: " + scannedName + "\n" +
"Minutes: " + scannedMin + "\n" +
"Seconds: " + scannedSec +
"\n-----------------------------------\n");
//add to the playlist if no errors
title.add(new Song(scannedName, scannedMin, scannedSec));
}
catch(InputMismatchException e) // handle when data is N/A
{
String error = scan.nextLine(); //consume the error and return to see where error is occurring
System.out.print( " ERROR (cause): " + error + "\n");
}
catch(NoSuchElementException e) // handle when no more data in file
{
endFile = true; //nothing in file set endFile
}
} //close try block
//close and return true
scan.close();
return true;
}// close loop
//return false if no file found
catch (FileNotFoundException e)
{
System.out.println("THERE IS NO FILE BRETHREN");
return false;
}
}// close method
下面是导致主类出现问题的代码
if (b.addSongs("revolver.txt"))
System.out.println("Songs in file revolver.txt added successfully");
System.out.printf("The playlist \"%s\" has a total playing time of %5.2f minutes\n", b.getName(), b.getPlayingTime());
System.out.printf("It includes the song \"%s\" with a playing time of %4.2f minutes\n", song, b.getPlayingTime(song));
System.out.printf("The longest song is \"%s\"\n", b.longestSong());
if (b.removeSong("Taxman"))
System.out.println("The song \"Taxman\" was removed successfully");
System.out.println("\n" + b); }
这是错误消息:
PLTest.java:32: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
b.addSongs("revolver.txt");
^
我的解决方案是在主类中添加FileNotFoundException throw,但正如我之前所说的._.我被禁止更改它。我不知道被调用的方法抛出异常后会发生什么错误。这是唯一发生的错误,当我将throw添加到主类时,一切都正常工作。
旁注:我试图把throw放到另一个方法中,但得到了一个重复的错误,当我刚刚删除throw时,这个错误就消失了。我不知道这是否相关,但我的下一个猜测是找到一种不用try/catch就能改变布尔值的方法?
1条答案
按热度按时间k97glaaz1#
用途
代替
并确保文本文件沿着src文件夹的旁边。霍韦异常将被解决。