线程“主”java.util.NoSuchElementException 中的异常:找不到行

Posted

技术标签:

【中文标题】线程“主”java.util.NoSuchElementException 中的异常:找不到行【英文标题】:Exception in thread "main" java.util.NoSuchElementException: No line found 【发布时间】:2015-12-08 05:36:25 【问题描述】:
details:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine<Scanner.java:1540>
at CarReader2.main<CarReader2.java:30>
that's the entirety of the error.

我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class CarReader2 
    String name, speed, acc;

    public CarReader2(String carName, String carSpeed, String carAcc)
    name = carName;
    speed = carSpeed;
    acc = carAcc;
    

    public String toString()
    return "Name of car: " +name+ "\nSpeed of car: " +speed+"\nAcceleration of car: " +acc+"\n";
    

    public static void main(String[] args) 

    File file = new File("carlist.txt");

    try 

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) 

            String c1Name = sc.nextLine();
            String c1Speed = sc.nextLine();
            String c1Acc = sc.nextLine();
            CarReader2 car1 = new CarReader2(c1Name,c1Speed,c1Acc);
            car1.speed = c1Speed;
            car1.acc = c1Acc;

            String c2Name = sc.nextLine();
            String c2Speed = sc.nextLine();
            String c2Acc = sc.nextLine();
            CarReader2 car2 = new CarReader2(c2Name,c1Speed,c1Acc);
            car2.speed = c2Speed;
            car2.acc = c2Acc;

            System.out.println("Information on both cars");
            System.out.println("First car:");
            System.out.println(car1.toString());
            System.out.println("Second car:");
            System.out.println(car2.toString());
        
        sc.close();
     
    catch (FileNotFoundException e) 
        e.printStackTrace();



    
    

它应该从名为 carlist.txt 的文件中读取 2 辆汽车的数据,然后以正确的格式打印两辆汽车的数据。

carlist.txt 是一个文本文件,包含:

jonathan 3 7
dio 8 2

程序应该打印出来,

Information on both cars
First car:
Name of car: jonathan
Speed of car: 3
Acceleration of car: 7

Second car:
Name of car: dio
Speed of car: 8
Acceleration of car: 2

程序编译但不能正确运行,并在最顶部显示我发布的错误。

【问题讨论】:

【参考方案1】:

您使用的 nextLine 方法错误。名称、速度和加速度在同一行,但您使用 3 个 nextLine 方法来读取它们。当您尝试从一个只有 2 行的文件中读取 6 行时,就会发生这种情况。使用sc.next() 而不是sc.nextLine()

【讨论】:

没想到这么简单,非常感谢!【参考方案2】:

您阅读的行数过多。您的文件中只有两行,但您正在尝试阅读 6。您可以将文本文件更改为:

jonathan 
3 
7
dio 
8 
2

或者您可以阅读一行并拆分出您想要的信息。

【讨论】:

以上是关于线程“主”java.util.NoSuchElementException 中的异常:找不到行的主要内容,如果未能解决你的问题,请参考以下文章

Android 异步操作Android 线程切换 ( 判定当前线程是否是主线程 | 子线程中执行主线程方法 | 主线程中执行子线程方法 )

子线程怎么不阻塞主线程

QT中UI主窗口如何与子线程相互传递参数

java 子线程 回调 主线程

C++怎么在主线程中使用子线程的数据? 比如说主线程中有一个数组,如何在子线程中调用这个数组

EventBus事件通信框架 ( 发送事件 | 判断发布线程是否是主线程 | 子线程切换主线程 | 主线程切换子线程 )