使用Scanner类获取NoSuchElementException

时间:2018-01-19 23:02:33

标签: java java.util.scanner stringtokenizer nosuchelementexception

从“|”读取时,我得到了臭名昭着的NoSuchElementException使用扫描仪类分隔的文本文件。我正在使用每个标记的值,并使用setter方法将它们分配给单独的类中的值。我似乎无法查明错误。

这是我的代码:

void readFromFile(String fileName)
{
    operas.clear();

    Scanner input = new Scanner(new File(fileName));

    while(input.hasNextLine())
    {
        String line = input.nextLine();
        Opera opera = new Opera();

        StringTokenizer stringTokenizer = new StringTokenizer(line, "|");

        while(stringTokenizer.hasMoreTokens())
        {
            opera.setTitle(stringTokenizer.nextToken());
            opera.setComposer(stringTokenizer.nextToken());
            opera.setYear(Integer.parseInt(stringTokenizer.nextToken()));
            opera.setCity(stringTokenizer.nextToken());
            opera.setSynopsis(stringTokenizer.nextToken());
            opera.setLink(stringTokenizer.nextToken());

        }
        operas.add(opera);
    }

    input.close();
}

文本文件是这样写的(对不起,它太冗长了):

Giulio Cesare|George Frideric Handel|1724|London|Tells the story loosely based on the events of the Roman Civil War (48-47 B.C.) in which Julius Caesar has defeated Pompey and gone to Alexandria in search of him. The kingdom, ruled by Cleopatra and younger brother Ptolemy, is met by Pompey pleading for refuge from his conqueror.|https://www.youtube.com/watch?v=M1UmvCaobDg
Carmen|Georges Bizet|1875|Paris|Set in Seville around the year 1830, the opera deals with the love and jealousy of Don José, who is lured away from his duty as a soldier and his beloved Micaëla by the gypsy factory-girl Carmen, whom he allows to escape from custody.|https://www.youtube.com/watch?v=zTDMvyj4TFg
Die ZauberFlote|Wolfgang Amadeus Mozart|1791|Vienna|The Queen of the Night persuades Prince Tamino to rescue her daughter Pamina from captivity under the high priest Sarastro; instead, he learns the high ideals of Sarastro's community and seeks to join it. Separately, then together, Tamino and Pamina undergo severe trials of initiation, which end in triumph, with the Queen and her cohorts vanquished. The earthy Papageno, who accompanies Tamino on his quest, fails the trials completely but is rewarded anyway with the hand of his ideal female companion Papagena.|https://www.youtube.com/watch?v=Fm-4LdLFr_E
Il Barbiere di Siviglia|Gioachino Rossini|1816|Rome|Count Almaviva comes in disguise to the house of Doctor Bartolo and serenades Rosina, whom Bartolo keeps confined to the house. Figaro the barber, who knows all the town's secrets and scandals, explains to Almaviva that Rosina is Bartolo's ward, not his daughter, and that the doctor intends to marry her.|https://www.youtube.com/watch?v=p97ym1HeCNI
Tosca|Giacomo Puccini|1900|Rome|Tosca is tale of romance over politics; featuring a heroic painter, a despicable ruler and an opera superstar, Tosca herself!|https://www.youtube.com/watch?v=xGDhQwsgMBQ
Salome|Richard Strauss|1905|Dresden|Under the bright moonlight, guard captain, Narraboth, intensely watches Princess Salome, with whom he is madly in love, from a terrace above the banquet hall as she dines with her stepfather and his court.|https://www.youtube.com/watch?v=kInyoCPyFb0
War and Peace|Sergei Prokofiev|1944|Moscow|Based on Tolstoy's literature of War and Peace, the world-weary Prince Andrei Bolkonsky encounters the youthful Natasha Rostova, first in the country, then at a ball in St Petersburg. Enchanted, he asks for her hand in marriage. Unfortunately Natasha has also aroused the curiosity of the dissolute Anatol Kuragin.|https://www.youtube.com/watch?v=2nhOeGhWWkU
Dido and Aeneas|Henry Purcell|1689|London|Tells the tale of the legendary Queen of Carthage, Dido, and the Trojan refugee prince, Aeneas. When Aeneas and his crew become shipwrecked in Carthage, he and the Queen fall in love. In the meantime, witches plot Dido's destruction.|https://www.youtube.com/watch?v=Q3Vs3YXQp5U
Norma|Vincenzo Bellini|1831|Milan|Gaul has been conquered by the Romans. Oroveso, the Arch-Druid longs to lead a Gallic rebellion against the colonial forces. He and all the others wait for the signal to be given by his daughter, the Druid High Priestess Norma. But Norma has fallen in love with the Roman Proconsul, Pollione, and given birth to two children. They have been brought up in secrecy by her confidante Clotilde. Norma still loves Pollione but he has fallen in love with a novice priestess, Adalgisa.|https://www.youtube.com/watch?v=GN75XDDm_DI
Rigoletto|Giuseppe Verdi|1851|Venice|Its tragic story revolves around the licentious Duke of Mantua, his hunch-backed court jester Rigoletto, and Rigoletto's beautiful daughter Gilda. A curse is placed on both the Duke and Rigoletto by a courtier whose daughter the Duke has seduced with Rigoletto's encouragement. The curse comes to fruition when Gilda falls in love with the Duke and sacrifices her life to save him from assassins hired by her father.|https://www.youtube.com/watch?v=nlr9jygEgwM

我收到的错误:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
    at Operas.OperasGUI.readFromFile(OperasGUI.java:118)
    at Operas.OperasGUI.<init>(OperasGUI.java:45)
    at Operas.OperasGUI.main(OperasGUI.java:607)

另一个注意事项是第118行的错误是我设置年份的行,这是我正在解析原始值的唯一行。不确定这与它有什么关系。

有什么建议吗?如果需要更多代码或信息,我很乐意提供它。

谢谢。

编辑: 这是我完整的Operas课程:

package Operas;

public class Opera {

    private String title;
    private String composer;
    private int year;
    private String city;
    private String synopsis;
    private String link;

    public Opera(){
        title = "";
        composer = "";
        year = 0;
        city = "";
        synopsis = "";
        link = "";
    }

    public Opera(String title, String composer, int year, String city,
            String synopsis, String link)
    {
        this.title = title;
        this.composer = composer;
        this.year = year;
        this.city = city;
        this.synopsis = synopsis;
        this.link = link;
    }

    public Opera(Opera anotherOpera)
    {
        title = anotherOpera.title;
        composer = anotherOpera.composer;
        year = anotherOpera.year;
        city = anotherOpera.city;
        synopsis = anotherOpera.synopsis;
        link = anotherOpera.link;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getComposer() {
        return composer;
    }

    public void setComposer(String composer) {
        this.composer = composer;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSynopsis() {
        return synopsis;
    }

    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    @Override
    public String toString()
    {
        return "Opera{Title = " + title + ", Composer = " + composer + ", Year = " + year + 
                ", City = " + city + ", Synopsis = " + synopsis + ", Link = " + link + '}';
    }

    public boolean equals(Opera opera)
    {
        return this.getTitle().equalsIgnoreCase(opera.getTitle()) &&
                this.getComposer().equalsIgnoreCase(opera.getComposer());
    }
}

不确定是否有帮助。

1 个答案:

答案 0 :(得分:-2)

不确定你在这里做错了什么,我认为我的代码模仿你的代码是:

主要

    package helpMe;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.StringTokenizer;

    import javax.swing.plaf.synth.SynthSeparatorUI;

    public class getIt {

        static ArrayList readFromFile(String fileName) throws FileNotFoundException
        {

            ArrayList<Opera> a = new ArrayList<Opera>();

            Scanner input = new Scanner(new File(fileName));

            while(input.hasNextLine())
            {
                String line = input.nextLine();
                Opera opera = new Opera();

                StringTokenizer stringTokenizer = new StringTokenizer(line, "|");

                while(stringTokenizer.hasMoreTokens())
                {
                    opera.setTitle(stringTokenizer.nextToken());
                    opera.setComposer(stringTokenizer.nextToken());
                    opera.setYear(Integer.parseInt(stringTokenizer.nextToken()));
                    opera.setCity(stringTokenizer.nextToken());
                    opera.setSynopsis(stringTokenizer.nextToken());
                    opera.setLink(stringTokenizer.nextToken());

                }
                a.add(opera);
            }

            input.close();
            return a;
        }

        public static void main(String [] args) throws FileNotFoundException {
            ArrayList<Opera> a = new ArrayList<Opera>();
            a = readFromFile("thisIsAFile");
            for(int i = 0; i< a.size(); i++) {
                Opera o = a.get(i);
                System.out.println(o.toString());
            }
        }
    }

OPERA CLASS:

    package helpMe;

public class Opera {

    private String Title;
    private String City;
    private int Year;
    private String Composer;
    private String Synopsis;
    private String Link;

    public Opera(String t, String c, int y, String co, String s, String l) {
        Title = t;
        City = c;
        Year = y;
        Composer = co;
        Synopsis = s;
        Link = l;
    }

    public Opera() {
        Title = "";
        City = "";
        Year = 0;
        Composer = "";
        Synopsis = "";
        Link = "";
    }

    public String setTitle(String t) {
        return Title = t;
    }

    public String setCity(String c) {
        return City = c;
    }

    public int setYear(int y) {
        return Year = y;
    }

    public String setComposer(String co) {
        return Composer = co;
    }

    public String setSynopsis(String s) {
        return Synopsis = s;
    }

    public String setLink(String l) {
        return Link = l;
    }
    public String toString() {
        String s = Title + City + Composer;
        return s;
    }
}

文字文件

    Giulio Cesare|George Frideric Handel|1724|London|Tells the story loosely based on the events of the Roman Civil War (48-47 B.C.) in which Julius Caesar has defeated Pompey and gone to Alexandria in search of him. The kingdom, ruled by Cleopatra and younger brother Ptolemy, is met by Pompey pleading for refuge from his conqueror.|https://www.youtube.com/watch?v=M1UmvCaobDg
Carmen|Georges Bizet|1875|Paris|Set in Seville around the year 1830, the opera deals with the love and jealousy of Don José, who is lured away from his duty as a soldier and his beloved Micaëla by the gypsy factory-girl Carmen, whom he allows to escape from custody.|https://www.youtube.com/watch?v=zTDMvyj4TFg
Die ZauberFlote|Wolfgang Amadeus Mozart|1791|Vienna|The Queen of the Night persuades Prince Tamino to rescue her daughter Pamina from captivity under the high priest Sarastro; instead, he learns the high ideals of Sarastro's community and seeks to join it. Separately, then together, Tamino and Pamina undergo severe trials of initiation, which end in triumph, with the Queen and her cohorts vanquished. The earthy Papageno, who accompanies Tamino on his quest, fails the trials completely but is rewarded anyway with the hand of his ideal female companion Papagena.|https://www.youtube.com/watch?v=Fm-4LdLFr_E
Il Barbiere di Siviglia|Gioachino Rossini|1816|Rome|Count Almaviva comes in disguise to the house of Doctor Bartolo and serenades Rosina, whom Bartolo keeps confined to the house. Figaro the barber, who knows all the town's secrets and scandals, explains to Almaviva that Rosina is Bartolo's ward, not his daughter, and that the doctor intends to marry her.|https://www.youtube.com/watch?v=p97ym1HeCNI
Tosca|Giacomo Puccini|1900|Rome|Tosca is tale of romance over politics; featuring a heroic painter, a despicable ruler and an opera superstar, Tosca herself!|https://www.youtube.com/watch?v=xGDhQwsgMBQ
Salome|Richard Strauss|1905|Dresden|Under the bright moonlight, guard captain, Narraboth, intensely watches Princess Salome, with whom he is madly in love, from a terrace above the banquet hall as she dines with her stepfather and his court.|https://www.youtube.com/watch?v=kInyoCPyFb0
War and Peace|Sergei Prokofiev|1944|Moscow|Based on Tolstoy's literature of War and Peace, the world-weary Prince Andrei Bolkonsky encounters the youthful Natasha Rostova, first in the country, then at a ball in St Petersburg. Enchanted, he asks for her hand in marriage. Unfortunately Natasha has also aroused the curiosity of the dissolute Anatol Kuragin.|https://www.youtube.com/watch?v=2nhOeGhWWkU
Dido and Aeneas|Henry Purcell|1689|London|Tells the tale of the legendary Queen of Carthage, Dido, and the Trojan refugee prince, Aeneas. When Aeneas and his crew become shipwrecked in Carthage, he and the Queen fall in love. In the meantime, witches plot Dido's destruction.|https://www.youtube.com/watch?v=Q3Vs3YXQp5U
Norma|Vincenzo Bellini|1831|Milan|Gaul has been conquered by the Romans. Oroveso, the Arch-Druid longs to lead a Gallic rebellion against the colonial forces. He and all the others wait for the signal to be given by his daughter, the Druid High Priestess Norma. But Norma has fallen in love with the Roman Proconsul, Pollione, and given birth to two children. They have been brought up in secrecy by her confidante Clotilde. Norma still loves Pollione but he has fallen in love with a novice priestess, Adalgisa.|https://www.youtube.com/watch?v=GN75XDDm_DI
Rigoletto|Giuseppe Verdi|1851|Venice|Its tragic story revolves around the licentious Duke of Mantua, his hunch-backed court jester Rigoletto, and Rigoletto's beautiful daughter Gilda. A curse is placed on both the Duke and Rigoletto by a courtier whose daughter the Duke has seduced with Rigoletto's encouragement. The curse comes to fruition when Gilda falls in love with the Duke and sacrifices her life to save him from assassins hired by her father.|https://www.youtube.com/watch?v=nlr9jygEgwM

<强>输出

    Giulio CesareLondonGeorge Frideric Handel
CarmenParisGeorges Bizet
Die ZauberFloteViennaWolfgang Amadeus Mozart
Il Barbiere di SivigliaRomeGioachino Rossini
ToscaRomeGiacomo Puccini
SalomeDresdenRichard Strauss
War and PeaceMoscowSergei Prokofiev
Dido and AeneasLondonHenry Purcell
NormaMilanVincenzo Bellini
RigolettoVeniceGiuseppe Verdi

不确定这是否有帮助,但它似乎工作正常,我从根本没有问题阅读文本文件。