Win
Win

Reputation: 217

Exception in thread "main" java.util.NoSuchElementException: No line found

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.

My code:

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();



    }
    }
}

It's supposed to read data of 2 cars from a file called carlist.txt, then print the data of both cars in the correct format.

carlist.txt is a text file containing:

jonathan 3 7
dio 8 2

And the program is supposed to print out,

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

The program compiles but doesn't run correctly and shows the error i posted at the very top.

Upvotes: 4

Views: 3804

Answers (2)

Ryan
Ryan

Reputation: 2084

You are reading too many lines. There are only two lines in your file, but you are trying to read 6. You can change your text file to:

jonathan 
3 
7
dio 
8 
2

or you can read one line and split out the information you want.

Upvotes: 0

uoyilmaz
uoyilmaz

Reputation: 3105

You're using nextLine method wrong. Name, speed and acceleration are in the same line, but you're using 3 nextLine methods to read them. That's what happens when you try to read 6 lines from a file that only has 2 lines in it. use sc.next() instead of sc.nextLine().

Upvotes: 1

Related Questions