Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法抛出自定义异常_Java - Fatal编程技术网

Java 无法抛出自定义异常

Java 无法抛出自定义异常,java,Java,我正在尝试分析文件中的相册列表。我的列表中有22个相册,列表中的一个项目是重复的,另一个项目的形式不正确。我应该抛出两个异常并在控制台上打印有用的消息。我的InputMismatchException工作正常,虽然我的程序应继续读取文件输入,但跳过发生异常的列表中的相册对象/行。另一个异常是DuplicateAlbumException,这是一个自定义异常。此异常应忽略重复项,请在控制台上打印一条有用的消息,指出已忽略重复项,并且只阅读该项目一次。以下是我的包含相册输入的txt文件:top20a

我正在尝试分析文件中的相册列表。我的列表中有22个相册,列表中的一个项目是重复的,另一个项目的形式不正确。我应该抛出两个异常并在控制台上打印有用的消息。我的InputMismatchException工作正常,虽然我的程序应继续读取文件输入,但跳过发生异常的列表中的相册对象/行。另一个异常是DuplicateAlbumException,这是一个自定义异常。此异常应忽略重复项,请在控制台上打印一条有用的消息,指出已忽略重复项,并且只阅读该项目一次。以下是我的包含相册输入的txt文件:
top20albums.txt

Led Zeppelin    IV  1971
Led Zeppelin    II  1969
Fleetwood Mac   Rumors  1977
Pink Floyd  The Wall    1979
XXXXX   XXXXXXXXX   XXXX
The Clash   London Calling  1979
The Beatles Abbey Road  1969
Van Morrison    Moondance   1971
Talking Heads   Fear of Music   1979
Who Who's Next  1971
The Beatles Rubber Soul 1965
Cure    Kiss Me, Kiss Me, Kiss Me   1987
Violent Femmes  Violent Femmes  1982
Pink Floyd  The Wall    1979
Soul Coughing   Ruby Vroom  1994
James   Laid    1993
Liz Phair   Exile in Guyville   1993
Pink Floyd  Dark Side of the Moon   1973
Police  Zenyatta Mondatta   1980
Led Zeppelin    Houses of the Holy  1973
Soul Coughing   Irresistable Bliss  1996
Replacements    Tim 1985
预期产出:

java AlbumList top20albums.txt
ERROR: Line 5: Invalid input for year. Skipping line
ERROR: Line 14: Duplicate album 'The Wall' by Pink Floyd
Album Rankings from top20albums.txt
Rank Title Artist Year
---- ------------------------------ -------------------- ----
1 IV Led Zeppelin 1971
2 II Led Zeppelin 1969
3 Rumors Fleetwood Mac 1977
4 The Wall Pink Floyd 1979
5 London Calling The Clash 1979
6 Abbey Road The Beatles 1969
7 Moondance Van Morrison 1971
8 Fear of Music Talking Heads 1979
9 Who's Next Who 1971
10 Rubber Soul The Beatles 1965
11 Kiss Me, Kiss Me, Kiss Me Cure 1987
12 Violent Femmes Violent Femmes 1982
13 Ruby Vroom Soul Coughing 1994
14 Laid James 1993
15 Exile in Guyville Liz Phair 1993
16 Dark Side of the Moon Pink Floyd 1973
17 Zenyatta Mondatta Police 1980
18 Houses of the Holy Led Zeppelin 1973
19 Irresistible Bliss Soul Coughing 1996
20 Tim Replacements 1985 
我在eclipse控制台上的输出:

ERROR: Line 5: Invalid input for year. Skipping line.

Rank Title                  Artist       Year
---- -----                  ------       -----

1    IV                             Led Zeppelin         1971
2    II                             Led Zeppelin         1969
3    Rumors                         Fleetwood Mac        1977
4    The Wall                       Pink Floyd           1979
到目前为止,我的努力如下:

第1类

第二类


我希望我的代码块有足够的信息和解释让您理解我的担忧。但我要明确地再说一遍:为什么我的扫描仪在出现不匹配异常后停止读取文件输入?

问题在于
.nextInt()
抛出
输入不匹配异常
导致控件在
循环时退出
。重构代码以

try {

   Scanner input = new Scanner(inFile);
   input.useDelimiter("\\t|[\\n\\r\\f]+");

   while (input.hasNext()) {

    try{
       String artist = input.next();
       String title = input.next();
       int year = input.nextInt();

   Album albumObject = new Album(title,artist,year,rank);

     addAlbum(albumObject);
      count ++;
      rank++;
}
catch (InputMismatchException exception)
{
    System.out.println("ERROR: Line "+(count+1)+": Invalid input for  year. Skipping line.");
}

    }
 }
// This exception will not occur unless I give it a file input that does not  exist.
catch (FileNotFoundException exception)
{
    System.out.println("The file  was not found.");
}
 /* This exception works fine.However, the Scanner should continue reading  the file
 * inputs just skipping the 5th line where the mismatch occur.My program for some reason
 * is not printing any more input after skipping the line and that is my  problem.
 */

我希望这能解决您的问题

问题在于
。nextInt()
抛出
输入不匹配异常
,导致控件在
循环时退出
。重构代码以

try {

   Scanner input = new Scanner(inFile);
   input.useDelimiter("\\t|[\\n\\r\\f]+");

   while (input.hasNext()) {

    try{
       String artist = input.next();
       String title = input.next();
       int year = input.nextInt();

   Album albumObject = new Album(title,artist,year,rank);

     addAlbum(albumObject);
      count ++;
      rank++;
}
catch (InputMismatchException exception)
{
    System.out.println("ERROR: Line "+(count+1)+": Invalid input for  year. Skipping line.");
}

    }
 }
// This exception will not occur unless I give it a file input that does not  exist.
catch (FileNotFoundException exception)
{
    System.out.println("The file  was not found.");
}
 /* This exception works fine.However, the Scanner should continue reading  the file
 * inputs just skipping the 5th line where the mismatch occur.My program for some reason
 * is not printing any more input after skipping the line and that is my  problem.
 */

我希望这能解决您的问题

首先,我们将使用一套,因为您不需要重复的相册

第二,我们要说每一行都有一张专辑。这样做的原因是,当出现输入不匹配异常时,扫描仪将无法前进。然后还有一个问题,扫描仪不在下一行

Set<Album> albums = new HashSet<>();
try( 
        BufferedReader reader = Files.newBufferedReader(
            inFile.toPath(), Charset.forName("UTF8")
        )
    ){
    String line;
    while((line = reader.readline())!=null){
        Scanner input = new Scanner(line);
        input.useDelimiter("\\t|[\\n\\r\\f]+");
        int rank = 0;
        try{
            String artist = input.next();
            String title = input.next();
            int year = input.nextInt();
            Album albumObject = new Album(title,artist,year,rank);
            if(albums.add(albumObject){
                rank++;
            } else{
                throw new DuplicateAlbumException("album: " + title + " exists");
            }
        } catch(InputMissmatchException exc){
            //print out an error about a bad line.
        } catch(DuplicateAlbumException exc){
            //print out an error about a duplicate album.
        }
    }
} catch(IOException e){
    //problem with the file 
}

首先,我们将使用一个集合,因为您不需要重复的相册

第二,我们要说每一行都有一张专辑。这样做的原因是,当出现输入不匹配异常时,扫描仪将无法前进。然后还有一个问题,扫描仪不在下一行

Set<Album> albums = new HashSet<>();
try( 
        BufferedReader reader = Files.newBufferedReader(
            inFile.toPath(), Charset.forName("UTF8")
        )
    ){
    String line;
    while((line = reader.readline())!=null){
        Scanner input = new Scanner(line);
        input.useDelimiter("\\t|[\\n\\r\\f]+");
        int rank = 0;
        try{
            String artist = input.next();
            String title = input.next();
            int year = input.nextInt();
            Album albumObject = new Album(title,artist,year,rank);
            if(albums.add(albumObject){
                rank++;
            } else{
                throw new DuplicateAlbumException("album: " + title + " exists");
            }
        } catch(InputMissmatchException exc){
            //print out an error about a bad line.
        } catch(DuplicateAlbumException exc){
            //print out an error about a duplicate album.
        }
    }
} catch(IOException e){
    //problem with the file 
}


太多的代码。这样的问题应该只包含相关的、最少的代码和实际错误,以帮助回答问题。请查看帮助文档以了解有关如何完成此操作的更多信息:我不完全确定,但据我所知,当程序在try/catch语句中遇到错误时,它将终止正在执行的任何进程,因此,当异常发生时,它很可能会停止读取文件。@pczeus一些声誉很高的用户告诉我,我的问题没有足够的信息,这就是我尽力解释的原因。围绕
addAlbum(…)
如果您不想在出现异常时停止循环,请使用
调用try…catch..
。这同样适用于
输入不匹配异常
异常。顺便说一下,音乐的好选择:)代码太多了。这样的问题应该只包含相关的、最少的代码和实际错误,以帮助回答问题。请查看帮助文档以了解有关如何完成此操作的更多信息:我不完全确定,但据我所知,当程序在try/catch语句中遇到错误时,它将终止正在执行的任何进程,因此,当异常发生时,它很可能会停止读取文件。@pczeus一些声誉很高的用户告诉我,我的问题没有足够的信息,这就是我尽力解释的原因。围绕
addAlbum(…)
如果您不想在出现异常时停止循环,请使用
调用try…catch..
。这同样适用于
输入不匹配异常
异常。顺便说一句,音乐的不错选择:)嗨,你的解决方案只读取前11行。它仍然不会抛出重复异常,即,它停止在第5行,但不会读取第6行和下一次重复后的行。是的,这是对
的回答,但我要明确地再说一遍:为什么我的扫描器在不匹配异常之后停止读取文件输入?
在相同的行上继续,您可以继续在while循环中引入异常处理程序来处理要继续处理的异常。嗯,您当时就收到了。我非常感谢您的进一步帮助,但谢谢:)。我可以使用您提到的while循环事实获得它,直到前19行。但是,它不会在不匹配异常之后立即打印第6行。而且,它会打印三次不匹配异常消息,而不是一次。@af如果扫描器没有前进,因此它会得到第一个missmatch异常,然后它前进2次,并尝试获取下一个int,但您只在下一个标题上。然后它向前推进两倍,并试图得到下一个int,但你是艺术家。然后它前进了两次,你又回到了过去的一年,所以它正确地得到了过去的一年,你又回到了正轨。但您又抛出了两张额外的相册。您好,您的解决方案只读取前11行。它仍然不会抛出重复异常,即它在第5行停止,但不会读取第6行和下一次重复后的行。是的,这是对
的回答,但我要明确地再说一遍:为什么我的扫描器在不匹配异常之后停止读取文件输入?
在相同的行上继续,您可以继续在while循环中引入异常处理程序来处理要继续处理的异常。嗯,您当时就收到了。我非常感谢您的进一步帮助,但谢谢:)。我可以使用您提到的while循环事实获得它,直到前19行。但是,它不会在不匹配异常之后立即打印第6行。而且,它会打印三次不匹配异常消息,而不是仅仅一次。如果扫描器没有前进,那么它会得到第一个mis
Set<Album> albums = new HashSet<>();
try( 
        BufferedReader reader = Files.newBufferedReader(
            inFile.toPath(), Charset.forName("UTF8")
        )
    ){
    String line;
    while((line = reader.readline())!=null){
        Scanner input = new Scanner(line);
        input.useDelimiter("\\t|[\\n\\r\\f]+");
        int rank = 0;
        try{
            String artist = input.next();
            String title = input.next();
            int year = input.nextInt();
            Album albumObject = new Album(title,artist,year,rank);
            if(albums.add(albumObject){
                rank++;
            } else{
                throw new DuplicateAlbumException("album: " + title + " exists");
            }
        } catch(InputMissmatchException exc){
            //print out an error about a bad line.
        } catch(DuplicateAlbumException exc){
            //print out an error about a duplicate album.
        }
    }
} catch(IOException e){
    //problem with the file 
}
@Override
public int hashCode(){
    return title.hashCode() + artist.hashCode();
}