java - 线程 "main"java.util.NoSuchElementException : No line found 中的异常

标签 java exception line element program-entry-point

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

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

最佳答案

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

关于java - 线程 "main"java.util.NoSuchElementException : No line found 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32527172/

相关文章:

Java 字符串构造函数

java - 如何获取我们自定义的AlertDialog的值?

vba - 用vba绘制图表(不是图表对象而是图表)

c - C 代码的 R 内联编译在 Windows 上失败

java - @WebParam 在 jetty 服务 SOAP 中始终为空

java - 如何使 Activity 不全屏

java - 抛出异常而不中断方法的执行

spring - 使用 OpenSessionInViewFilter 时出现 No bean named 'sessionFactory' 错误

.net - 添加服务引用时出错 : Type is a recursive collection data contract which is not supported

ios - 按照滑动路径在滑动手指上用箭头画线