java - 获取异常 java.util.NoSuchElementException : No line found while reading from file?

标签 java debugging

代码之前工作正常,但即使没有进行任何更改也会出现运行时异常。该程序的目的是成为棒球运动员的数据库,其中包含他们的一些统计数据 - 可以在下面的代码中看到。当我现在运行程序时,出现此错误

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at Assig3.getBatters(Assig3.java:47)
    at Assig3.<init>(Assig3.java:62)
    at Assig3.main(Assig3.java:248)

这个错误并没有真正帮助我解决任何问题,我完全不知道,一夜之间发生的问题是什么。无论如何,这是代码,它分为三个文件,这些文件从第四个纯文本文件接收数据

import java.util.*;
import java.io.*;

// CS 0401  Assignment 3 main program class.  Note how this class is set up
// with instance variables and methods.  The idea is that the main program is itself an
// object and the methods being called are parts of the object that implement the various
// requirements.  I have implemented the initial reading of the data from the file to
// get you started.  You must add the menu and all of its required functionality.

// Note that this program WILL NOT COMPILE until you have completed the Batter and BatterDB
// classes to some extent.  They do not have to be totally working but all of the methods
// used here must be implemented in order for this code to compile.

public class Assig3
{
    private BatterDB theDB;
    private Batter currBatter;
    private Scanner inScan;
    private String fName;

    // Note how this method is working.  It first reads the number of Batters from the
    // file, then for each Batter it gets the names, creates the object, and mutates it
    // with the instance methods shown.  Finally, it adds the new object to the BatterDB
    // object.
    public void getBatters(String fName) throws IOException
    {
        Batter currB;
        File inFile = new File(fName);
        Scanner inScan = new Scanner(inFile);
        int numBatters = inScan.nextInt();
        inScan.nextLine();
        for (int i = 0; i < numBatters; i++)
        {
            String first = inScan.nextLine();
            String last = inScan.nextLine();
            currB = new Batter(first, last);

            int ab, h, d, t, hr;    
            ab = inScan.nextInt();  inScan.nextLine();
            currB.setBats(ab);
            h = inScan.nextInt();   inScan.nextLine();
            currB.setHits(h);
            d = inScan.nextInt();   inScan.nextLine();
            currB.setDoubles(d);
            t = inScan.nextInt();   inScan.nextLine();
            currB.setTriples(t);
            hr = inScan.nextInt();  inScan.nextLine();
            currB.setHR(hr);
            theDB.addBatter(currB);
        }
    }

    // Constructor is really where the execution begins.  Initialize the
    // database (done for you) and then go into the main interactive loop (you
    // must add this code).
    public Assig3(String fstring) throws IOException
    {
        Scanner reader = new Scanner(System.in);
        fName = fstring;
        Batter currB;
        theDB = new BatterDB(); // <-- there used to be a 2 in there
        getBatters(fName);
        System.out.println("The database has been loaded");
        System.out.println(theDB.toString());

        commandPrompter();
        String command = reader.next();
        while(!command.equals("8")){

            if(command.equals("1")){
                System.out.println(theDB.toString());
            } else if(command.equals("2")){
                System.out.println("First name: ");
                String first = reader.next();

                System.out.println("Last name: ");
                String last = reader.next();

                currB = new Batter(first, last);

                int ab, h, d, t, hr;
                System.out.print("How many times did he bat: ");
                ab = reader.nextInt();
                currB.setBats(ab);

                System.out.println("How many hits: ");
                h = reader.nextInt();
                if(h>ab || h<0){
                    while(h>ab || h<0){
                        System.out.println("Invalid try again: ");
                        h = reader.nextInt();
                    }
                }
                currB.setHits(h);

                System.out.println("How many doubles: ");
                d = reader.nextInt();
                if(d>ab || d<0 || d>h){
                    while(d>ab || d<0){
                        System.out.println("Invalid try again: ");
                        d = reader.nextInt();
                    }
                }
                currB.setDoubles(d);

                System.out.println("How many triples: ");
                t = reader.nextInt();
                if(t>ab || t<0 || t>h || (t+d)>h){
                    while(t>ab || t<0 || t>h || (t+d)>h){
                        System.out.println("Invalid try again: ");
                        t = reader.nextInt();
                    }
                }
                currB.setTriples(t);

                System.out.println("How many Homeruns: ");
                hr = reader.nextInt();
                if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
                    while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
                        System.out.println("Invalid try again: ");
                        hr = reader.nextInt();
                    }
                }
                currB.setHR(hr);
                theDB.addBatter(currB);

            } else if(command.equals("3")){
                System.out.println("Player first name: ");
                String firstNameSearch = reader.next();
                System.out.println("Player last name: ");
                String lastNameSearch = reader.next(); 

                currB = theDB.findBatter(firstNameSearch, lastNameSearch);
                if(currB == null){
                    System.out.println("The player you wish to see in not in this database");
                } else {
                    System.out.println(currB.toString());
                }

            } else if(command.equals("4")){
                System.out.println("Player first name: ");
                String firstNameSearch = reader.next();
                System.out.println("Player last name: ");
                String lastNameSearch = reader.next(); 

                currB = theDB.findBatter(firstNameSearch, lastNameSearch);

                if(currB == null){
                    System.out.println("The player you wish to remove in not in this database");
                } else {
                    System.out.println("The player has been removed from the database");
                    theDB.removeBatter(currB);
                }
            } else if(command.equals("5")){
                System.out.println("Player first name: ");
                String firstNameSearch = reader.next();
                System.out.println("Player last name: ");
                String lastNameSearch = reader.next(); 

                currB = theDB.findBatter(firstNameSearch, lastNameSearch);

                if(currB == null){
                    System.out.println("The player you wish to edit in not in this database");
                } else {
                    int ab, h, d, t, hr;
                    System.out.print("How many times did he bat: ");
                    ab = reader.nextInt();
                    currB.setBats(ab);

                    System.out.println("How many hits: ");
                    h = reader.nextInt();
                    if(h>ab || h<0){
                        while(h>ab || h<0){
                            System.out.println("Invalid try again: ");
                            h = reader.nextInt();
                        }
                    }
                    currB.setHits(h);

                    System.out.println("How many doubles: ");
                    d = reader.nextInt();
                    if(d>ab || d<0 || d>h){
                        while(d>ab || d<0){
                            System.out.println("Invalid try again: ");
                            d = reader.nextInt();
                        }
                    }
                    currB.setDoubles(d);

                    System.out.println("How many triples: ");
                    t = reader.nextInt();
                    if(t>ab || t<0 || t>h || (t+d)>h){
                        while(t>ab || t<0 || t>h || (t+d)>h){
                            System.out.println("Invalid try again: ");
                            t = reader.nextInt();
                        }
                    }
                    currB.setTriples(t);

                    System.out.println("How many Homeruns: ");
                    hr = reader.nextInt();
                    if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
                        while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
                            System.out.println("Invalid try again: ");
                            hr = reader.nextInt();
                        }
                    }
                    currB.setHR(hr);
                }

            } else if(command.equals("6")){
                theDB.sortName();
            } else if(command.equals("7")){
                theDB.sortAve();
            } else {
                System.out.println("What the heck that was not an option, bye.");
            }


            commandPrompter();
            command = reader.next();
        }
        theDB.toStringFile();
        System.out.println("Thanks for using the DB! Bye.");

    }

    private void commandPrompter(){
        System.out.println("Please choose one of the options below: ");
        System.out.println("1) Show the list of players");
        System.out.println("2) Add a new player");
        System.out.println("3) Search for a player");
        System.out.println("4) Remove a player");
        System.out.println("5) Update a player");
        System.out.println("6) Sort the list alphabetically");
        System.out.println("7) Sort the list by batting average");
        System.out.println("8) Quit the program [list will be saved]");
    }

    // Note that the main method here is simply creating an Assig3 object.  The
    // rest of the execution is done via the constructor and other instance methods
    // in the Assig3 class.  Note also that this is using a command line argument for
    // the name of the file.  All of our programs so far have had the "String [] args"
    // list in the header -- we are finally using it here to read the file name from the
    // command line.  That name is then passed into the Assig3 constructor.
    public static void main(String [] args) throws IOException
    {
        Assig3 A3 = new Assig3(args[0]);
    }
}

BatterDB:

import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import java.io.PrintWriter;
// CS 0401 BatterDB class
// This class is a simple database of Batter objects.  Note the
// instance variables and methods and read the comments carefully.  You minimally
// must implement the methods shown.  You may also need to add some private methods.
// To get you started I have implemented the constructor and the addBatter method for you.

public class BatterDB
{
    private ArrayList<Batter> theBatters = new ArrayList<Batter>(); // ArrayList of Batters
    private int num;                // int to store logical size of DB

    // Initialize this BatterDB
    public BatterDB()
    {
        num = 0;
    }

    // Take already created Batter and add it to the DB.  This is simply putting
    // the new Batter at the end of the array, and incrementing the int to
    // indicate that a new movie has been added.  If no room is left in the 
    // array, resize to double the previous size, then add at the end.  Note that
    // the user never knows that resizing has even occurred, and the resize()
    // method is private so it cannot be called by the user.
    public void addBatter(Batter b)
    {
        theBatters.add(b);
        num++;
    }

    // Remove and return the Batter that equals() the argument Batter, or
    // return null if the Batter is not found.  You should not leave a gap in
    // the array, so elements after the removed Batter should be shifted over.
    public Batter removeBatter(Batter b)
    {
        theBatters.remove(b);
        return b;
    }

    // Return logical size of the DB
    public int numBatters()
    {
        return theBatters.size();
    }

    // Resize the Batter array to that specified by the argument
    private void resize(int newsize)
    {
        //Don't need this now that it's an array list!
    }

    // Find and return the Batter in the DB matching the first and last
    // names provided.  Return null if not found.
    public Batter findBatter(String fName, String lName)
    {
        Batter currentB = null;
        String fullNameSearch = lName+","+fName;
        for(int i=0; i<theBatters.size(); i++){
            if(fullNameSearch.toUpperCase().equals(theBatters.get(i).getName().toUpperCase())){
                currentB = theBatters.get(i);

            }
        }
        return currentB;
         //change
    }

    // Sort the DB alphabetically using the getName() method of Batters for
    // comparison
    public void sortName()
    {
        int j;

        for ( j = 0;  j < theBatters.size()-1;  j++)
        {
            if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
            {                                             // ascending sort
                Collections.swap(theBatters, j, j+1);
                j=0;
            }
            if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
            {                                             // ascending sort
                Collections.swap(theBatters, j, j+1);
                j=0;
            }
        }
    }

    // Sort the DB from high to low using the getAve() method of Batters for
    // comparison
    public void sortAve()
    {
        int j;

        for ( j = 0;  j < theBatters.size()-1;  j++)
        {

            if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
            {                                             // ascending sort
                Collections.swap(theBatters, j, j+1);
                j=0;
            }
            if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
            {                                             // ascending sort
                Collections.swap(theBatters, j, j+1);
                j=0;
            }
        }
    }

    // Return a formatted string containing all of the Batters' info.  Note
    // that to do this you should call the toString() method for each Batter in
    // the DB.
    public String toString()
    {
        return theBatters.stream().map(b -> b.toString()).collect(Collectors.joining("\n"));
    }

    // Similar to the method above, but now we are not formatting the
    // string, so we can write the data to the file.
    public void toStringFile()
    {
        try{
            PrintWriter writer = new PrintWriter("batters.txt", "UTF-8");
            writer.println(theBatters.size());
            for(int i=0; i<theBatters.size(); i++){
                String[] parts = theBatters.get(i).getName().split(",");
                String fName= parts[1];
                String lName = parts[0];
                writer.println(fName);
                writer.println(lName);
                writer.println(theBatters.get(i).getAtBats());
                writer.println(theBatters.get(i).getHits());
                writer.println(theBatters.get(i).getDoubles());
                writer.println(theBatters.get(i).getTriples());
                writer.println(theBatters.get(i).getHomeRuns());
            }
            writer.close();
        } catch (Exception e) {
           System.out.println("Did not work, sorry :(");
        }
    }

}

击球手:

public class Batter {

    private String firstName;
    private String lastName;
    private int atBats;
    private int hits;
    private int doubles;
    private int triples;
    private int homeRuns;

    public Batter(String fName, String lName){
        firstName = fName;
        lastName = lName;
    }
    public void setBats(int batCount){
        atBats = batCount;
    }
    public void setHits(int hitCount){
        hits = hitCount;
    }
    public void setDoubles(int doubleCount){
        doubles = doubleCount;
    }
    public void setTriples(int tripleCount){
        triples = tripleCount;
    }
    public void setHR(int homeRunCount){
        homeRuns = homeRunCount;
    }
    public double getAve(){
        double one = this.hits;
        double two = this.atBats;
        double average = (one / two);
        return average;
    }
    public int getAtBats(){
        return this.atBats;
    }
    public int getHits(){
        return this.hits;
    }
    public int getDoubles(){
        return this.doubles;
    }
    public int getTriples(){
        return this.triples;
    }
    public int getHomeRuns(){
        return this.homeRuns;
    }
    public String getName(){
        String fullName = this.lastName + "," + this.firstName;
        return fullName;
    }
    public boolean equals(){

        return true;
    }
    public String toString(){
        return "Player: "+getName()+"\nAt Bats: "+this.atBats+"\nHits: "+this.hits+"\nDoubles: "+this.doubles+"\nTriples: "+this.triples+"\nHome Runs: "+this.homeRuns;
    }
}

batters.txt(文本文件):

5
Cannot
Hit
635
155
12
7
6
Major
Hitter
610
290
50
25
65
The
Hulk
650
300
0
0
300
Iron
Man
700
600
300
0
300
Herb
Weaselman
600
200
20
15
30

最佳答案

Error :
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at Assig3.getBatters(Assig3.java:47)
    at Assig3.<init>(Assig3.java:62)
    at Assig3.main(Assig3.java:248)

描述:

NoSuchElementException mean whatever your code is trying to read is   not there 
mean there is no element which you are trying to read.
At line 47 i.e hr = inScan.nextInt();  inScan.nextLine(); 
your code is trying to read an int and nextline 
but there is no next line in your source file 
which basically will happen in the last iteration of your loop

原因是当您的代码到达最后一个文件条目时,即 30 然后

hr = inScan.nextInt();  inScan.nextLine();
     //^^^ this will read 30
                  // but         ^^^ there is no next line and hence the exception 

解决方案:使用hasNextLine或在文件末尾使用回车符添加下一行

hr = inScan.nextInt();  
if(inScan.hasNextLine())
      inScan.nextLine();

或者您可以操作文件,然后只需使用 Enter 在文件末尾添加一个空行(我不推荐)

关于java - 获取异常 java.util.NoSuchElementException : No line found while reading from file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734286/

相关文章:

java - Apache 客户端缓存 jar

java - 如何从java在matlab中加载图像

java - 可通过方法参数运行

iphone - iOS 崩溃报告,例如在 Beta 测试期间

debugging - Go语言中常见的陷阱有哪些?

c++ - 如何在复杂的 cpp 项目中打印 gdb 中的 Armadillo 矩阵?

java - 如何配置 testsuit 始终将常量注入(inject)到类的所有实例的 @value 私有(private)字段中

java - java中没有这样的方法错误

xml - 无法在 visual studio 2015RC 社区中调试/启动/停止 xsl

debugging - Fortran if 测试创建的段错误