java.util.NoSuchElementException:找不到行

新手上路,请多包涵

当我通过扫描仪读取文件时,我的程序出现运行时异常。

 java.util.NoSuchElementException: No line found
   at java.util.Scanner.nextLine(Unknown Source)
   at Day1.ReadFile.read(ReadFile.java:49)
   at Day1.ParseTree.main(ParseTree.java:17)

我的代码是:

 while((str=sc.nextLine())!=null){
    i=0;
    if(str.equals("Locations"))
    {
        size=4;
        t=3;
        str=sc.nextLine();
        str=sc.nextLine();
    }
    if(str.equals("Professions"))
    {
        size=3;
        t=2;
        str=sc.nextLine();
        str=sc.nextLine();
    }
    if(str.equals("Individuals"))
    {
        size=4;
        t=4;
        str=sc.nextLine();
        str=sc.nextLine();
    }

int j=0;
String loc[]=new String[size];
while(j<size){
    beg=0;
    end=str.indexOf(',');
    if(end!=-1){
        tmp=str.substring(beg, end);
        beg=end+2;
    }
    if(end==-1)
    {
        tmp=str.substring(beg);
    }
    if(beg<str.length())
        str=str.substring(beg);
    loc[i]=tmp;
    i++;

    if(i==size ){
        if(t==3)
        {
            location.add(loc);
        }
        if(t==2)
        {
            profession.add(loc);
        }
        if(t==4)
        {
            individual.add(loc);
        }
        i=0;
    }
    j++;
    System.out.print("\n");
}

原文由 Ashish Panery 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

Scanner 你需要检查是否有下一行 hasNextLine()

所以循环变成

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

是读者在 EOF 上返回 null

当然,在这段代码中,这取决于输入是否正确格式化

原文由 ratchet freak 发布,翻译遵循 CC BY-SA 3.0 许可协议

我也遇到了那个问题。在我的例子中,问题是我关闭了其中一个功能中的扫描仪..

 public class Main
{
	public static void main(String[] args)
	{
		Scanner menu = new Scanner(System.in);
        boolean exit = new Boolean(false);
    while(!exit){
		String choose = menu.nextLine();
        Part1 t=new Part1()
        t.start();
	    System.out.println("Noooooo Come back!!!"+choose);
		}
	menu.close();
	}
}

public class Part1 extends Thread
{
public void run()
  {
     Scanner s = new Scanner(System.in);
     String st = s.nextLine();
     System.out.print("bllaaaaaaa\n"+st);
     s.close();
	}
}


上面的代码做了同样的解释,解决方案是只在 main 关闭一次扫描器。

原文由 agr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题