2016-10-27 32 views
0

这是我第一次在mye相对较短的编程生活中遇到了NoSuchElementException。我做了一些研究,并且没有发现任何帖子追溯到一个类似的情况,在许多情况下,编码器只有not put in hasNextLine(),从而导致异常。另一个例子是当编码器试图read two lines consequently,这也导致了错误。第三个尝试得到了解决方案与check for an empty line at the end,这我觉得可能在于更接近我的问题。然而,我不觉得这是我在寻找解决方案这是我的代码:。NoSuchElementException:没有找到行(使用hasNextLine()

import java.util.HashMap; import java.util.Scanner; import java.io.*; 

class DVDAdministrasjon 
{ 
    private String eier; 
    private String laaner; 
    private boolean utlaant; 
    private String tittel; 

    private HashMap<String, DVD> dvdListe = new HashMap<String, DVD>(); 
    private HashMap<String, Person> personListe = new HashMap<String, Person>(); 

    public void lesDVDarkiv(String filnavn) throws Exception 
    { 
    Scanner fil = new Scanner(new File(filnavn)); 
    String curDVD = ""; 
    String inData; //lagrer data fra filen 

    while (fil.hasNextLine()) 
    { 
     inData = fil.nextLine(); 
     while (inData.equals("")) //Hopper over eventuelle linjeskift 
     { 
     inData = fil.nextLine(); 
     } 
     if (inData.equals("-")) 
     { 
     inData = fil.nextLine(); 
     personListe.put(inData, new Person(inData)); 
     } 
     else 
     { 
     inData = fil.nextLine(); 
     curDVD = inData; 
     dvdListe.put(inData, new DVD(inData)); 
     if (curDVD.substring(0,1).equalsIgnoreCase("*")) 
     { 
      utlaant = true; 
     } 
     } 
    } 
    } 
} 

这里是主类:

import java.util.Scanner; import java.io.File;

class Oblig7Test1 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Scanner in = new Scanner(System.in); 
    DVDAdministrasjon dListe = new DVDAdministrasjon(); 
    dListe.lesDVDarkiv("dvdarkiv2.txt"); 
    } 
} 

请记住这个程序将扩展到远远超出现在可见的程度。这也是一个任务,但我只关心为什么我得到错误。该文件由一些行中包含多个单词的行组成,在某些行的开始处包含“*”,在某些行之间包含“ - ”作为分隔符。

错误看起来是这样的:

java.util.NoSuchElementException: No line found 
    at java.util.Scanner.nextLine(Scanner.java:1540) 
    at DVDAdministrasjon.lesDVDarkiv(DVDAdministrasjon.java:29) 
    at Oblig7Test1.main(Oblig7Test1.java:9) 
+0

如果您阅读getNextLine()的javadoc,您可以看到“使此扫描器超越当前行并返回跳过的输入”。那么如何访问多行来检查一个hasNextLine()? –

+0

@LyjuIEdwinson'getNextLine()' - 这是从哪里来的? –

+0

您需要在每次调用nextLine()之前检查'hasNextLine()'。你刚刚读到文件末尾 – Tibrogargan

回答

1

在你的代码中,我添加了一些意见

while (fil.hasNextLine()) // if it enters here it has more lines 
{ 
    inData = fil.nextLine(); // OK can read as hasNextLine returned true 
    while (inData.equals("")) 
    { 
    inData = fil.nextLine(); // NO guarantee that there is a `nextLine` 

不理解你的代码完全我建议,如果你需要读取下一行则您应该将contune置于循环的顶部,或者使用if (fil.hasNextLine())

+0

我没有想到这一点,但它解决了我的问题。我理解这个推理:-)我已经明确了解了一些东西,并且会在学习更多的时候牢记这一点! 感谢您的时间! –

0

再次测试在第二个while循环中执行以下操作:

while (inData.equals("") && **fil.hasNextLine()**) //this second conditions ensure that it will enter while only if it has next line to read, else it passes to the next if condition 
     { 
     inData = fil.nextLine(); 
     }