加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:09:34 所属栏目:Java 来源:网络整理
导读:details:Exception in thread "main" java.util.NoSuchElementException: No line foundat java.util.Scanner.nextLineScanner.java:1540at CarReader2.mainCarReader2.java:30that's the entirety of the error. 我的代码: import java.io.File;import jav
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,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().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读